2012-09-25 33 views
3

如何在字符串"I am in the EU."内存在整个单词(即"EU"),而不是像"I am in Europe."这样的匹配案例?正则表达式找到整个单词

基本上,我想要某种形式的正则表达式,即"EU"两边都有非字母字符。

+3

看看单词边界\ b – gtgaxiola

回答

6

.*\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"); 
     } 

    } 
2

你可以做类似

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(); 

看一看的docs for Pattern。 。

+0

+1我忘了''我周围的正则表达式:( – gtgaxiola

+0

不幸的是,Java文档没有真正告诉一个字边界是什么会这样的项目更深入的挖掘:HTTPS:/ /stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regexes – akauppi