如何使用Java使正则表达式找到街道/道路?

1 java regex pattern-matching

我试图在Java中制作一个可以粗略地用于匹配某些街道名称的正则表达式.我想这样做,以便给出以下字符串:

然后有人决定去大街喝一杯

"高街"一词将匹配.这就是前面的单词和"街道"这个词来获得街道名称.我尝试过这样的事情:

Pattern.compile("(\\w+\\s*(road|street|square|rd|st|sq)\\W+)");
Run Code Online (Sandbox Code Playgroud)

但这是失败的,似乎Java想要匹配整个句子,但我只是对几句话感兴趣.我也尝试了一些不情愿的量词,但似乎没有任何效果.

任何帮助/建议将不胜感激.谢谢!

aio*_*obe 5

确保你使用Matcher.find而不是Matcher.matches.

这在我的机器上工作正常:

String s = "Then someone decided to go to the high street for a drink";

Pattern p = Pattern.compile("(\\w+\\s*(road|street|square|rd|st|sq)\\W+)");

Matcher m = p.matcher(s);

System.out.println(m.find());   // prints true
System.out.println(m.group());  // prints "high street"
Run Code Online (Sandbox Code Playgroud)

您还可以简化表达式:

\w+\s*(road|street|square|rd|st|sq)\W
Run Code Online (Sandbox Code Playgroud)

要么

\w+\s*(r(oa)?d|st(reet)?|sq(uare)?)\W
Run Code Online (Sandbox Code Playgroud)

(给出与上面相同的输出)