简体   繁体   中英

Grouping Regular Expression in Python

I'm having a problem. I'm trying to figure out what is the regular expression for the following situation, where I want to match one of the follwoing if returned back.

               ABC 1 or 
               ABC 1 0  or
               ABC 1 0 1  or 
               ABC 1 0 1 0 or etc

I'm trying the following to acheive this but its only matching the first string (ABC 1).

               regular expression: ABC (1|0)+

I have been trying to figure this out for a long time and I can't seem to figure it out. Could someone please help?

Thanks

If you want to make sure it's first a 1, then a 0, then another 1, then a 0 etc, you might use this:

re.match(r'ABC(?: 1(?: 0|$))+$', s)

regex101 demo

EDIT: If you don't care about the order, you can use this:

re.match(r'ABC(?: [01])+$', s)

ABC1(01)*0?

ABC, then 1, then zero or more 0 1, and finally an optional 0. Assuming you don't want white spaces, of course.

If you want a single space after each "part":

ABC 1( 0 1)*( 0)?

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