Regex to match exact word in a string

14 / Oct / 2010 by Vishal Sahu 6 comments

Hi,

In my recent grails project, i needed to check the occurrence of a word in a string. I could have used contains() method of groovy , but the problem with contains() is that it also matches the word if the word is contained as a substring in any word.
I searched a lot, but nothing worked out so i decided to use Regular expression for it. With the help of my colleague,we came out with a simple regex to find the occurrence of exact word in a long string, even if the word is surrounded by comma, full-stop or some other character.

The regex is:-

     String matchingWord="string"  // word to find
     String longString="it is a very long string. find the exact word in it"  

 // method to return the result

    def pattern = /\b${matchingWord}\b/
    def matcher = longString =~ pattern
    return matcher.getCount() ? true : false


The method returns true if the exact word is found in the string. But it will return false if the word is occurring as substring.

It worked in my case.
Hope it helps.

Vishal Sahu
vishal@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (6)

  1. gopinath

    suppose i have
    $string = “windows 2008 R2 server 12″;

    In the above string i need to grep 2008 alone ..
    it may change to 2012 , 2010 whatever .. a perl script regex should grep only 2008..
    please help on this

    Reply
  2. vasanth

    Hi i have to check the whole word including spaces,

    eg: need to work
    /\bneed to work\b/

    is this the correct regEx for word –> need to work?

    Reply
  3. Mike Miller

    Nice, I’ve had a couple instances of having to do this too. Here’s another option:

    return ((longString =~ /\b${matchingWord}\b/).find())

    Reply

Leave a comment -