Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find whole words

Tags:

java

regex

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.

like image 525
Skizit Avatar asked Sep 25 '12 00:09

Skizit


People also ask

Which regex matches the whole words dog or cat?

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.

What does \b mean in regex?

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).

What is a word boundary regex?

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.


1 Answers

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

    }
like image 177
gtgaxiola Avatar answered Sep 28 '22 15:09

gtgaxiola