简体   繁体   中英

How to find matching braces in string?

I'm looping through a templated dictionary doing substitutions. The values in the dictionary look like this:

foo{sub1}{sub2}bar{sub3}

where foo , bar , and subN can be any random text (not containing a brace character).

I'm trying to identify {sub1} , {sub2} , and {sub3} in the list. I can parse the characters myself but assume there is a 1-liner solution.

Anybody see it?

>>> re.findall('{.*?}', 'foo{sub1}{sub2}bar{sub3}')
['{sub1}', '{sub2}', '{sub3}']

findall finds... all occurrences of the pattern and returns a list. Use finditer if you want an iterator.

Note, though, that if your string contains stuff like {abc{def}} , the pattern won't work.

You can use the following regex:

>>> s = 'foo{sub1}{sub2}bar{sub3}'
>>> re.findall('{([^}]+)}', s)
['sub1', 'sub2', 'sub3']

We capture everything that's inside { and } , then findall simply returns a list with all matched groups.

If you want to keep the { and } as part of the matched strings, simply remove the group:

re.findall('{[^}]+}', s)

regex solution is two-line solution, because you must import module before. :) There is a simple tricky solution with list generation and split method:

>>> [x.split('}')[0] for x in 'foo{sub1}{sub2}bar{sub3}'.split('{') if '}' in x]
['sub1', 'sub2', 'sub3']

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