How do i find string in nested brackets
Lets say I have a string
regex = r"(\(\w*?\))"
matches = re.findall(regex, s)
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']