Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a word suffix only when it appears as part of larger word?

The following regexp matches the trailing 's' on a word or word fragment:

/s\b/i

Is it possible to only match the trailing s if it is a part of a larger word?

That is, for example, the suffix s in the string "words" is matched, but if someone entered a string "s" by itself, there would be no match.

Thanks for your advice

like image 286
Trev Avatar asked Dec 08 '25 22:12

Trev


2 Answers

Like this where \w patches any 'word' character followed by s followed by word boundary

/\ws\b/i
like image 67
Billy Moon Avatar answered Dec 11 '25 12:12

Billy Moon


The standard answer is

/\ws\b/i

as was given before, but there are caveats. Make sure that Perl's definition of \w is suitable for your use. Perl thinks that '_' is a word character, so this will match '2_s' as a suffixed word. You can use \p{IsAlpha} instead if you want just alphabetic characters.

You still have the issue that the above will think that '214bs' is the "word" 214b with an 's' on the end. Instead you might want something like this:

/\b\p{IsAlpha}+s\b/

It all depends on what your input looks like.

like image 24
swestrup Avatar answered Dec 11 '25 12:12

swestrup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!