简体   繁体   中英

regex partial match for several different groups

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

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

A
A9
AA9

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

A
AA
AAA
AAA9

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

AAA
AA9
AA9A

group 4 regex [0-9]{1,2}[AZ]{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.

This regex will match all the strings you have provided:

^[A-Z]+[0-9]*(\s+[A-Z]+[0-9]*)+$

and unlimited words.

怎么样:

^[A-Z]{1,2}[0-9]?(?:\s+[A-Z]{1,3}[0-9]?(?:\s+[A-Z]{2,3}[0-9]?[A-Z]?(?:\s+[0-9]{1,2}[A-Z]{1,2}[0-9]?)?)?)?$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM