Regex negation?

Lester Peabody picture Lester Peabody · Dec 25, 2013 · Viewed 36.7k times · Source

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?

Answer

Jerry picture Jerry · Dec 25, 2013

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.