正则表达式查找整个单词

5
我该如何判断一个完整的单词,例如"EU",是否存在于字符串"I am in the EU."中,而不匹配类似"I am in Europe."的情况?
基本上,我需要一种可以匹配非字母字符的单词正则表达式,例如"EU"

3
请查看单词边界 \b。 - gtgaxiola
3个回答

8

.*\bEU\b.*

 public static void main(String[] args) {
       String regex = ".*\\bEU\\b.*";
       String text = "EU is an acronym for  EUROPE";
       //String text = "EULA should not match";


       if(text.matches(regex)) {
           System.out.println("It matches");
       } else {
           System.out.println("Doesn't match");
       }

    }

4
你可以尝试这样做:
String str = "I am in the EU.";
Matcher matcher = Pattern.compile("\\bEU\\b").matcher(str);
if (matcher.find()) {
   System.out.println("Found word EU");
}

3

使用带有单词边界的模式:

String str = "I am in the EU.";

if (str.matches(".*\\bEU\\b.*"))
    doSomething();

请查看Pattern文档了解更多关于Pattern的信息。


不幸的是,Java文档并没有真正说明什么是单词边界。这篇SO文章深入探讨了这个问题:https://dev59.com/33M_5IYBdhLWcg3wjj-r - akauppi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接