Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex pattern to match alternating subpatterns

Tags:

regex

php

pcre

I'm trying to devise a regex pattern (in PHP) which will allow for any alternation of two subpatterns. So if pattern A matches a group of three letters, and B matches a group of 2 numerals, all of these would be OK:

aaa
aaa66bbb
66
67abc
12abc34def56ghi78jkl

I don't mind which subpattern starts or ends the sequence, just that after the first match, the subpatterns must alternate. I'm totally stumped by this - any advice will be gratefully received!

like image 830
George Crawford Avatar asked Apr 09 '26 12:04

George Crawford


1 Answers

Here's a general solution:

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

It's a simple alternation--three letters or two digits--but the negative lookaheads ensure that the same alternative is never matched twice in a row. Here's a slightly more elegant solution just for PHP:

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

Instead of typing the same subpatterns multiple times, you can put them capturing groups and use (?1), (?2), etc. to apply them again wherever else you want--in this case, in the lookaheads.

like image 189
Alan Moore Avatar answered Apr 11 '26 01:04

Alan Moore