Python 3.4 - Regular Expressions For Matching Innermost curly brackets

1.5k views Asked by At

I am trying to code a Python regular expression for matching innermost curly brackets, i.e. curly brackets which can contain any number of characters other than another pair of curly brackets. As an example, I would like the following code:

re.findall(r'\{.*^\{.*^\}.*\}',"aaa.bbb{ccc.ddd{eee.fff}ggg.hhh}")

to return the following:

['{eee.fff}']

but at the moment I only get a 'no match':

[]

The regular expression means - well from what I understand of regular expressions so far - "match any pattern which starts with an opening curly bracket, followed by any number of characters, followed by no opening bracket, followed by any number of characters, followed by no closing brackets, followed by any number of characters, followed by a closing bracket.

Any idea how to improve/correct the above regular expression ?

1

There are 1 answers

2
alecxe On BEST ANSWER

Instead use [^{}]+ to match one or more characters that are not curly braces:

>>> re.findall(r'\{[^{}]+\}', "aaa.bbb{ccc.ddd{eee.fff}ggg.hhh}")
['{eee.fff}']