Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to find brackets in a string

Tags:

python

regex

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?

like image 612
user Avatar asked Jun 10 '15 19:06

user


4 Answers

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)
like image 142
TigerhawkT3 Avatar answered Oct 06 '22 01:10

TigerhawkT3


Use the following (Closing square bracket must be escaped inside character class):

brackets=re.search(r"[(){}[\]]+",s)
                           ↑
like image 45
karthik manchala Avatar answered Oct 05 '22 23:10

karthik manchala


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.

like image 34
Michał Trybus Avatar answered Oct 05 '22 23:10

Michał Trybus


You could also do this without a regex:

s="(a(vdwvndw){}]"
keep = {"(",")","[","]","{","}"}
print("".join([ch for ch in s if ch in keep]))
((){}]
like image 27
Padraic Cunningham Avatar answered Oct 06 '22 01:10

Padraic Cunningham