I have a string which has multiple brackets. Let says
s="(a(vdwvndw){}]"
I want to extract all the brackets as a separate string.
I tried this:
>>> brackets=re.search(r"[(){}[]]+",s)
>>> brackets.group()
But it is only giving me last two brackets.
'}]'
Why is that? Shouldn't it fetch one or more of any of the brackets in the character set?
You have to escape the first closing square bracket.
r'[(){}[\]]+'
To combine all of them into a string, you can search for anything that doesn't match and remove it.
brackets = re.sub( r'[^(){}[\]]', '', s)
Use the following (Closing square bracket must be escaped inside character class):
brackets=re.search(r"[(){}[\]]+",s)
↑
The regular expression "[(){}[]]+"
(or rather "[](){}[]+"
or "[(){}[\]]+"
(as others have suggested)) finds a sequence of consecutive characters.
What you need to do is find all of these sequences and join them.
One solution is this:
brackets = ''.join(re.findall(r"[](){}[]+",s))
Note also that I rearranged the order of characters in a class, as ]
has to be at the beginning of a class so that it is not interpreted as the end of class definition.
You could also do this without a regex:
s="(a(vdwvndw){}]"
keep = {"(",")","[","]","{","}"}
print("".join([ch for ch in s if ch in keep]))
((){}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With