我如何找到字符串"EU"
中是否存在整个单词,即"I am in the EU."
,而不是匹配"I am in Europe."
等案例?
基本上,我想在"EU"
这个词的某种正则表达式中使用非字母字符。
答案 0 :(得分:7)
.*\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");
}
}
答案 1 :(得分:3)
使用带有字边界的模式:
String str = "I am in the EU.";
if (str.matches(".*\\bEU\\b.*"))
doSomething();
答案 2 :(得分: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");
}