Monday 24 June 2019

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.


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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...