2012-09-25 32 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