Using regex to detect ONLY double braces

Viewed 82

I wrote some code to grab everything between two curly braces along with the braces themselves

strings = re.findall('\{{.*?\}}',string)

However if the string contains mismatched brackets e.g "John is from {{city},{{country}}" this does not work correctly.

Is there a way to adjust my code so that I can only grab the matched brackets?

1 Answers

You can simply exclude the braces from the "contained string" with a character class:

strings = re.findall(r'\{\{[^{}]*\}\}', string)
Related