正则表达式来查找整个单词
如果在"I am in the EU."
这个字符串中存在一个单词,即"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"); }