regex partial match for several different groups

Posted by koral on Stack Overflow See other posts from Stack Overflow or by koral
Published on 2013-10-22T09:22:17Z Indexed on 2013/10/22 9:54 UTC
Read the original article Hit count: 307

Filed under:
|

I need regexp to match string build from several groups (A is any letter, 9 is any digit):

group 1 regex [A-Z]{1,2}[0-9]?

A
A9
AA9

group 2 regex [A-Z]{1,3}[0-9]?

A
AA
AAA
AAA9

group 3 regex [A-Z]{2,3}[0-9]?[A-Z]?

AAA
AA9
AA9A

group 4 regex [0-9]{1,2}[A-Z]{1,2}[0-9]?

9A
9AA
9A9
99A9

Not each group must be present but there must be all in correct order - I mean (digit is group number):

1
12
123
1234

So if there is present group 3 there must me all preceding groups present also.

As there are four groups (can be more), so alternative like

^[A-Z]{1,2}[0-9]{1}|[A-Z]{1,2}[0-9]{1}\s{1}[A-Z]{1}[0-9]?$

is not the best option as it would be complicated and difficult to maintain. Is there any solution with groups or something? The order of groups is important.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about regex