Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String negation using regular expressions

Is it possible to do string negation in regular expressions? I need to match all strings that do not contain the string "..". I know you can use ^[^\.]*$ to match all strings that do not contain "." but I need to match more than one character. I know I could simply match a string containing ".." and then negate the return value of the match to achieve the same result but I just wondered if it was possible.

like image 639
Paul Bevis Avatar asked Jul 20 '09 14:07

Paul Bevis


People also ask

How do you write a negation 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.

Which string methods are used with regular expression?

Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() .

What is '?' In regular expression?

It means "Match zero or one of the group preceding this question mark." It can also be interpreted as the part preceding the question mark is optional. In above example '?' indicates that the two digits preceding it are optional. They may not occur or occur at the most once.


2 Answers

You can use negative lookaheads:

^(?!.*\.\.).*$ 

That causes the expression to not match if it can find a sequence of two periods anywhere in the string.

like image 58
chaos Avatar answered Sep 19 '22 12:09

chaos


^(?:(?!\.\.).)*$ 

will only match if there are no two consecutive dots anywhere in the string.

like image 23
Tim Pietzcker Avatar answered Sep 17 '22 12:09

Tim Pietzcker