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

发布于 2024-12-10 04:00:58 字数 353 浏览 0 评论 0原文

我正在尝试用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

微凉徒眸意 2024-12-17 04:00:58

确保您使用 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"

您还可以稍微简化表达式:

\w+\s*(road|street|square|rd|st|sq)\W

or

\w+\s*(r(oa)?d|st(reet)?|sq(uare)?)\W

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

Make sure you use Matcher.find and not Matcher.matches.

This works fine on my machine:

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"

You could also simplify the expression a little:

\w+\s*(road|street|square|rd|st|sq)\W

or

\w+\s*(r(oa)?d|st(reet)?|sq(uare)?)\W

(gives the same output as above)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文