5

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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
Skizit
  • 43,506
  • 91
  • 209
  • 269

3 Answers3

8

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

    }
gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
4

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");
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
  • Unfortunately, Java docs don't really tell what a word boundary is. This SO item digs deeper: https://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regexes – akauppi Oct 25 '17 at 06:00