正则表达式找到整个单词

如何在字符串"I am in the EU." "EU"中存在整个单词,即"EU" ,我怎么才能找到"I am in the EU." 虽然不匹配"I am in Europe."这样的案件"I am in Europe."

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

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

使用带有字边界的图案:

 String str = "I am in the EU."; if (str.matches(".*\\bEU\\b.*")) doSomething(); 

看一下Pattern的文档 。

你可以做点什么

 String str = "I am in the EU."; Matcher matcher = Pattern.compile("\\bEU\\b").matcher(str); if (matcher.find()) { System.out.println("Found word EU"); }