Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I match an exact word in a string with a regex?

Tags:

regex

vba

I've been struggling to find solution to what sounds like a simple problem.

I need to find a word "HYD" (capital letters) in a text string. I need match to be exact. To clarify, any word/text that has "HYD" in it, but does not equal should not be matched. Exception are spaces and symbols.


Find in below examples:
text1 HYD text2
text1,HYD.text2

Ignore in below examples:
text1 HYDROtext2
text1 MYHYD text2

The closest I was able to get was following pattern:

objRegEx.Pattern = "[^a-z]HYD[^a-z]"

Problem with that is that it will not find "HYD" if string starts or ends with it.

like image 744
Trm Avatar asked Aug 05 '15 08:08

Trm


2 Answers

From the comments:

Use \b word boundary flags for your solution:

objRegEx.Pattern = "\bHYD\b"

Will hit only strings whose whole value is HYD, not strings where there is HYD embedded with some other characters.

like image 191
TylerH Avatar answered Sep 26 '22 19:09

TylerH


I've tested with the regex below and got the results you seem to need :)

/*HYD/*

I've tested via http://regexpal.com/

-EDIT:

The real answer you are looking for (i think) is https://stackoverflow.com/a/18936642/3462988

The pattern mentioned there selects the whole word containing HYD. \b(?=\w*[HYD])\w+\b

like image 20
Willem Avatar answered Sep 23 '22 19:09

Willem