Regex to find whole words
Solution 1:
.*\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");
}
}
Solution 2:
You could do something like
String str = "I am in the EU.";
Matcher matcher = Pattern.compile("\\bEU\\b").matcher(str);
if (matcher.find()) {
System.out.println("Found word EU");
}
Solution 3:
Use a pattern with word boundaries:
String str = "I am in the EU.";
if (str.matches(".*\\bEU\\b.*"))
doSomething();
Take a look at the docs for Pattern
.