Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex negation?

I'm playing Regex Golf (http://regex.alf.nu/) and I'm doing the Abba hole. I have the following regex that matches the wrong side entirely (which is what I was trying to do):

(([\w])([\w])\3\2)

However, I'm trying to negate it now so it matches the other side. I can't seem to figure that part out. I tried:

(?!([\w])([\w])\3\2)

But that didn't work. Any tips from the regex masters?

like image 362
Lester Peabody Avatar asked Dec 25 '13 15:12

Lester Peabody


People also ask

What is 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.

What is negative Lookbehind regex?

In negative lookbehind the regex engine first finds a match for an item after that it traces back and tries to match a given item which is just before the main match. In case of a successful traceback match the match is a failure, otherwise it is a success.

How can you negate characters in a set?

Negated Character Classes If you don't want a negated character class to match line breaks, you need to include the line break characters in the class. [^0-9\r\n] matches any character that is not a digit or a line break.


2 Answers

You can make it much shorter (and get more points) by simply using . and removing unnecessary parens:

^(?!.*(.)(.)\2\1)

It just makes sure that there's no "abba" ("abba" here means 4 letters in that particular order we don't want to match) in any part of the string without having to match the whole word.

like image 98
Jerry Avatar answered Sep 21 '22 23:09

Jerry


Using the explanation here: https://stackoverflow.com/a/406408/584663

I came up with: ^((?!((\w)(\w)\4\3)).)*$

like image 44
Bill Avatar answered Sep 21 '22 23:09

Bill