[regex] Invert match with regexp

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.

This question is related to regex pcre

The answer is


You can also do this (in python) by using re.split, and splitting based on your regular expression, thus returning all the parts that don't match the regex, splitting based on what doesn't match a regularexpression


Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string


It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*


Build an expression that matches, and use !match()... (logical negation) That's probably how grep does anyway...