Regular expression for finding brackets in a string

I have a line with several brackets. Let speak

s="(a(vdwvndw){}]" 

I want to extract all the brackets as a separate line.

I tried this:

 >>> brackets=re.search(r"[(){}[]]+",s) >>> brackets.group() 

But that only gives me the last two brackets.

 '}]' 

Why? Should it extract one or more of the brackets in the character set?

+5
source share
4 answers

You need to avoid the first closing square bracket.

 r'[(){}[\]]+' 

To combine all of them into a string, you can search for everything that does not match and delete.

 brackets = re.sub( r'[^(){}[\]]', '', s) 
+7
source

Use the following ( The closing square bracket must escape inside the character class ):

 brackets=re.search(r"[(){}[\]]+",s) ↑ 
+3
source

The regular expression "[(){}[]]+" (or rather, "[](){}[]+" or "[(){}[\]]+" (as others suggested)) finds the sequence consecutive characters. What you need to do is find all these sequences and join them.

One solution:

 brackets = ''.join(re.findall(r"[](){}[]+",s)) 

Note that I reordered the order of the characters in the class, since ] must be at the beginning of the class so that it is not interpreted as the end of the class definition.

+1
source

You can also do this without regex:

 s="(a(vdwvndw){}]" keep = {"(",")","[","]","{","}"} print("".join([ch for ch in s if ch in keep])) ((){}] 
+1
source

All Articles