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!
Just use the pattern like
/\b(([A-Za-z]{3,})+(s))\b/
Continuing from the PHP question Regex - How to search for singular or plural version of word
If you know what your search term is, it can be pretty simple. Here's a simple example I use in PHP to highlight all occurrences of a search term whether it is singular, simple plural (s), all lowercased or first letter uppercased:
[\w]+
has already matched the "s". The solution is to make[\w]+
match as few as possible, instead of as many as possible, with the "?" modifier. Thus: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.