Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert match with regexp [duplicate]

Tags:

regex

pcre

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.

like image 742
Joe Beda Avatar asked Jun 05 '09 18:06

Joe Beda


People also ask

What is ?! In regex?

Definition and Usage. The ?! n quantifier matches any string that is not followed by a specific string n.

How do you negate in regex?

Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.

How can I tell if two regex is same?

We say that two regular expressions R and S are equivalent if they describe the same language. In other words, if L(R) = L(S) for two regular expressions R and S then R = S.


2 Answers

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.

like image 181
Daniel Vandersluis Avatar answered Sep 26 '22 06:09

Daniel Vandersluis


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

like image 38
Joe Beda Avatar answered Sep 24 '22 06:09

Joe Beda