Regular expression to match a word or its prefix

NMGod picture NMGod · Aug 23, 2013 · Viewed 425.6k times · Source

I want to match a regular expression on a whole word.

In the following example I am trying to match s or season but what I have matches s, e, a, o and n.

[s|season]

How do I make a regular expression to match a whole word?

Answer

Jerry picture Jerry · Aug 23, 2013

Square brackets are meant for character class, and you're actually trying to match any one of: s, |, s (again), e, a, s (again), o and n.

Use parentheses instead for grouping:

(s|season)

or non-capturing group:

(?:s|season)

Note: Non-capture groups tell the engine that it doesn't need to store the match, while the other one (capturing group does). For small stuff, either works, for 'heavy duty' stuff, you might want to see first if you need the match or not. If you don't, better use the non-capture group to allocate more memory for calculation instead of storing something you will never need to use.