Illusionist Illusionist - 1 year ago 122
Python Question

Find all strings in nested brackets

How do i find string in nested brackets
Lets say I have a string


and I want to find all string in brackets (so wh, x, yz)

import re

regex = r"(\(\w*?\))"
matches = re.findall(regex, s)

The above code only finds yz

Can I modify this regex to find all matches?

Answer Source

Would a string split work instead of a regex?

match=[''.join(x for x in i if x.isalpha()) for i in s.split('(')]
['uv', 'wh', 'x', 'yz']
>>> match.pop(0)

You could pop off the first element because if it was contained in a parenthesis, the first position would be blank, which you wouldn't want and if it wasn't blank that means it wasn't in the parenthesis so again, you wouldn't want it.

Since that wasn't flexible enough something like this would work:

def match(string):
    unrefined_match=re.findall('\((\w+)|(\w+)\)', string)
    return [x for i in unrefined_match for x in i if x]

>>> match('uv(wh(x(yz))')
['wh', 'x', 'yz']

>>> match('a(b(c)de)')
['b', 'c', 'de']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download