Regular expression to match sets of numbers that are not equal or do not change

I have in mind the following question on this: Regular expression to match two numbers that are not equal

Now my other question:

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 is that the string P can be very long! - like this:

 P121315162324 

note that this is normal, since the "sets":

 12 13 14 15 16 23 24 

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

+4
source share
1 answer

Try the following:

 ^P(?:([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)))*$ 

If you want the numbers to be limited to [1-6], as in the previous question, change [0-9] to [1-6].

See how it works on the Internet: rubular


Here is a regex breakdown:

  ^ 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 ([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)) - corresponds to 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 (?:..)*(?:\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.
+2
source

Source: https://habr.com/ru/post/1343156/


All Articles