Friday, August 26, 2016

Regular expressions to match spaces, whole words and words with flexions

Regular expressions can be very useful but also very tricky. Here are a  few ones that have been tested in my VB.NET web applications.

Regular expression to match whole words surrounded by spaces


"\b\.?\s+" & yourword & "\b\s+"

\b\  stands for word boundary

\s+ stands for one or more spaces

Here is an improved regular expression without word boundaries that also looks for optional punctuation marks:

"([\.!?]?\s+" & yourword & "\s+)"

The optional group is enclosed in brackets, without them the group becomes mandatory.

Regular expression to match words with flexions

"((?i)\s+" & yourword  & "[en|e|er|s|es\b]{0,}[\.\,!?]?\s+)"

?i sets ignore case

en|e|er|s|es\b sets word flexions before word boundary

{0,} gets all forms

[\.\,!?] optional punctuation after word boundary

\s+ mandatory space

Please let me know how it works in your applications.









No comments:

Post a Comment