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 thi开发者_如何学Cs 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:
P121315162324
please notice this is ok since the "sets" are:
12 13 14 15 16 23 24
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?
Try this:
^P(?:([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)))*$
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.
精彩评论