简体   繁体   中英

python re backreference repeated elements

Let's say I have a string like this...

myStr = 'START1(stuff); II(morestuff); 8(lessstuff)'

...and I want to extract the string immediately before the parentheses, as well as the string within the parentheses: 1 , stuff , II , morestuff , 8 , lessstuff . I can achieve this using split(';') , etc., but I want to see if I can do it in one fell swoop with re.search() . I have tried...

test = re.search( r'START(?:([I0-9]+)\(([^)]+?)\)(?:; )?)*', myStr ).groups()

...or in a more readable format...

test = re.search( r'''
                  START         # This part begins each string
                  (?:           # non-capturing group
                    ([I0-9]+)   # capture label before parentheses
                    \(
                      ([^)]+?)  # any characters between the parentheses
                    \)
                    (?:; )?     # semicolon + space delimiter
                  )*
                  ''', myStr, re.VERBOSE ).groups()

...but I only get the last hit: ('8', 'lessstuff') . Is there a way to backreference multiple hits of the same part of the expression?

You can use this regex in findall to capture your text:

>>> myStr = 'START1(stuff); II(morestuff); 8(lessstuff)'
>>> print re.findall(r'(?:START)?(\w+)\(([^)]*)\)', myStr)
[('1', 'stuff'), ('II', 'morestuff'), ('8', 'lessstuff')]

RegEx Demo

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