Regular expression pattern to match alternating subpatterns

I am trying to create a regex pattern (in PHP) that will allow any alternation of two subpatterns. Therefore, if the pattern A corresponds to a group of three letters, and B corresponds to a group of 2 digits, they will all be in order:

aaa
aaa66bbb
66
67abc
12abc34def56ghi78jkl

I do not mind which subpattern starts or ends the sequence, only after the first match the subpatterns should alternate. I am completely shocked by this - any advice would be greatly appreciated!

+3
source share
4 answers

Here's a general solution:

^(?:[a-z]{3}(?![a-z]{3})|[0-9]{2}(?![0-9]{2}))+$

- , , . PHP:

/^(?:([a-z]{3})(?!(?1))|([0-9]{2})(?!(?2)))+$/

, , (?1), (?2) .., , - , lookaheads.

+2
"/^(?:$A(?:$B$A)*$B?|$B(?:$A$B)*$A?)\$/"

A, B A, , B... B, - A-B A, .

( $), . , $A $B - (, ), ? . $A "([a-zA-Z] {3})", $B "(\ d\d)".

, , - , , , ( , ), , .

+2

this ( ). , , , , .

0
/\b(?:(([a-z])\2\2)(?:(([0-9])\4)\1)*(?:([0-9])\5)?|(([0-9])\7)(?:(([a-z])\9\9)\6)*(?:([a-z])\10\10)?)\b/

char :

/\b(?:((\D)\2\2)(?:((\d)\4)\1)*(?:(\d)\5)?|((\d)\7)(?:((\D)\9\9)\6)*(?:(\D)\10\10)?)\b/

, . 3- char, 2- .

aaa
11
bbb22
33ccc
ddd44ddd
55eee55
fff66fff66
77ggg77ggg

aaa11bbb
0

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


All Articles