Monday, June 24, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...