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
.
Best Answer
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.
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...
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