Illusionist Illusionist - 23 days ago 10
Python Question

Find all strings in nested brackets

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

uv(wh(x(yz))


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

import re
s="uuv(wh(x(yz))"

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


The above code only finds yz

Can I modify this regex to find all matches?

LMc LMc
Answer

Would a string split work instead of a regex?

s='uv(wh(x(yz))'
match=[''.join(x for x in i if x.isalpha()) for i in s.split('(')]
>>>print(match)
['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']
Comments