简体   繁体   中英

Regular Expression to find brackets in a string

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]))
((){}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM