How would I find if a whole word, i.e. "EU"
, exists within the String "I am in the EU."
, while not also matching cases like "I am in Europe."
?
Basically, I'd like some sort of regex for the word i.e. "EU"
with non-alphabetical characters on either side.
You can use alternation to match a single regular expression out of several possible regular expressions. If you want to search for the literal text cat or dog, separate both options with a vertical bar or pipe symbol: cat|dog.
The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).
A word boundary, in most regex dialects, is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ( [0-9A-Za-z_] ). So, in the string "-12" , it would match before the 1 or after the 2. The dash is not a word character.
.*\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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With