Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match single word, with possible punctuation or pluralization at end (Regex)

I've been getting better at Regex, but I've come up with something that is beyond what I'm currently able to do.

I want to build a function to test (return true or false) to test to see if a word is found inside a string. But I wouldn't want to have a positive match if the word was found inside of another word. I would also like to build in the possibility of checking for pluralization.

Here are some examples of the results I'd expect to get:

Word to look for: "bar"

"Strings to search in" //what it should return as

"foo bar" //true

"foo bar." //true

"foo bar!" //true (would be true with any other punctuation before or after 'bar' too)

"foo bars." //true

"foo bares." //true (even though bares has a different meaning then bars, I would be okay with this returning true since I would need to check for words that pluralize with "es" and I wouldn't expect to build a regex to know which words pluralize with "s" and which to "es")

"my name is bart simpson" //false (bar is actually part of "bart")

"bart simpson went to the bar." //true

I'll be using javascript/jquery to check for matches

Thanks so much for the help!

like image 252
rgbflawed Avatar asked Feb 13 '13 16:02

rgbflawed


1 Answers

var rgx = new RegExp('\\b' + word + '(?:es|s)?\\b');
rgx.test(string);

This will return true for all of the strings you specified in your request. \b represents a "word boundary," which I believe is any character in \W (including period and exclamation point) as well as the start or end of the string.

like image 164
Explosion Pills Avatar answered Oct 14 '22 18:10

Explosion Pills