Regular expression to match sets of numbers that are not equal nor reversed

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I'm a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I am referring as a follow up on this question here: Regular expression to match two numbers that are not equal

Now my other question scenario is this:

P121324 - T  
P1212 - F - we got this covered in the message on link above (no same "sets")
P1221 - F - now new restriction -not even the reversed digits 12-21

But, the problem now is that the P string can be very long! - like this:


please notice this is ok since the "sets" are:


Now, I could make this in the code (PHP) by checking if there are repetitions, but I was wondering if this can be done with single regex command?

The answer, by Mark Byers, was:

Try this:


If you want the digits to be restricted to [1-6] like in your previous question then change [0-9] to [1-6].

See it working online: rubular

Here is a breakdown of the regular expression:

^          Start of string/line.
P          Literal P
(?:<snip>) Non-capturing group that matches a distinct pair of digits. See below.
*          Zero or more pairs (use + if you want to require at least one pair).
$          End of string/line.

Explanation of ([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)) - match one pair:

([0-9])    Match and capture the first digit. Later refered to as \1.
(?!\1)     Negative lookahead. The next character must not be the same as \1.
([0-9])    Match and capture a digit. Later refered to as \2.
(?!<snip>) Negative lookahead. Check that the pair doesn't occur again.

Explanation of (?:..)*(?:\1\2|\2\1) - try to find the same pair again:

(?:..)*       Match any number of pairs.
(?:\1\2|\2\1) Match either \1\2 or \2\1.
Written by Nikola Brežnjak