How to negate specific word in regex?

Bostone picture Bostone · Aug 6, 2009 · Viewed 758.8k times · Source

I know that I can negate group of chars as in [^bar] but I need a regular expression where negation applies to the specific word - so in my example how do I negate an actual bar, and not "any chars in bar"?

Answer

Chris Van Opstal picture Chris Van Opstal · Aug 6, 2009

A great way to do this is to use negative lookahead:

^(?!.*bar).*$

The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point. Inside the lookahead [is any regex pattern].