Invert match with regexp

Joe Beda picture Joe Beda · Jun 5, 2009 · Viewed 102.2k times · Source

With PCRE, how can you construct an expression that will only match if a string is not found.

If I were using grep (which I'm not) I would want the -v option.

A more concrete example: I want my regexp to match iff string foo is not in the string. So it would match bar would but not foobar.

Answer

Daniel Vandersluis picture Daniel Vandersluis · Jun 5, 2009

Okay, I have refined my regular expression based on the solution you came up with (which erroneously matches strings that start with 'test').

^((?!foo).)*$

This regular expression will match only strings that do not contain foo. The first lookahead will deny strings beginning with 'foo', and the second will make sure that foo isn't found elsewhere in the string.