1

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?

3
  • You want START1 or just 1? Commented May 6, 2016 at 17:25
  • 1
    If you're going to do that, it is imperative that you learn about the re.VERBOSE flag first: docs.python.org/2/library/re.html#re.VERBOSE ;-) Commented May 6, 2016 at 17:25
  • @heemayl Just 1. I could have left START off for the purposes of this question. Commented May 6, 2016 at 17:26

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I had forgotten about findall()!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.