Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex search and replace with optional plural

I'm a novice at regex, so hopefully some expert can just yawn at my question with an easy answer. I'm trying to find and replace words that start with a certain letter and keep them plural if they are plural.

So, for example, I want to replace replace the word "boy" with "band", and "boys" with "bands"

text.replace( /\b(b)[\w]+(s?)\b/gi, "<span style=\"font-weight:bold\">$1and$2<\/span>" );

However, $2 isn't coming up with the optional "s".

Thanks ahead of time!

like image 893
normmcgarry Avatar asked Jan 19 '23 05:01

normmcgarry


1 Answers

Simply change [\w]+ to [\w]+?.

This changes

from "greedy" (match as many characters as possible and only give characters up if forced to)
which means s? will not match because [\w]+ already did it for us. (wrong behavior)

to "lazy" (match as few characters as possible, only adding to the match if absolutely necessary)
which gives s? an opportunity to match. (correct behavior)

By the way: You can change [\w]+? to \w+? and it will work exactly the same.

like image 198
700 Software Avatar answered Jan 28 '23 03:01

700 Software