如何使用 Java 使正则表达式查找街道/道路?
我正在尝试用 Java 创建一个正则表达式,它可以粗略地用于匹配某些街道名称。我想做到这一点,以便给出以下字符串:
然后有人决定去大街喝一杯
“高街”这个词就匹配了。这就是前面的单词和单词“street”来获取街道名称。我尝试过这样的事情:
Pattern.compile("(\\w+\\s*(road|street|square|rd|st|sq)\\W+)");
但这失败了,似乎Java想要匹配整个句子,但我只对几个单词感兴趣。我也尝试了一些不情愿的量词,但似乎没有任何效果。
任何帮助/建议将不胜感激。谢谢!
I am trying to make a regex in Java which could crudely be used to match certain street names. I want to make it so that given the following string:
Then someone decided to go to the high street for a drink
The term "high street" would be matched. So that is the preceeding word and the word "street" to get the street name. I have tried something like this:
Pattern.compile("(\\w+\\s*(road|street|square|rd|st|sq)\\W+)");
But this is failing, it seems that Java wants to match the whole sentence, but I am just interested in a few words. I have tried a few reluctant quantifiers as well, but nothing seems to work.
Any help/suggestions will be much appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保您使用
Matcher.find
而不是Matcher.matches
。这在我的机器上运行良好:
您还可以稍微简化表达式:
or
(给出与上面相同的输出)
Make sure you use
Matcher.find
and notMatcher.matches
.This works fine on my machine:
You could also simplify the expression a little:
or
(gives the same output as above)