Reputation: 33
So, I have a RegEX equation and line of code that removes all curly braces from a string, but I want it to only remove the brackets when they are balanced
here is my line:
matches = re.findall(r'{{(.*?)}}', url)
string example: {{location.city}} output: location.city
But let's say the input string is:
{{location.city}}}}
I want the output to be location.city}}
I've been messing around with RegEx for a while and still haven't figured out how to do it.
Upvotes: 1
Views: 537
Reputation: 626961
You may require no }
after the closing }}
:
re.findall(r'{{(.*?)}}(?!})', url)
See the regex demo
The (?!})
is a negative lookahead that fails the match if there is a }
immediately on the right.
If the same is required with {{
, if there can be no {
before the {{
at the start, add a lookbehind:
re.findall(r'(?<!{){{(.*?)}}(?!})', url)
See this regex demo.
Upvotes: 2