How can one write a regex to remove all pairs of braces that contain nothing?
For example, {}
and {{}}
should be reduced to an empty string, but {{}
becomes {
and {{A}{}}
becomes {{A}}
.
I'm currently running s/\{\}//g
in a loop until the string length is fixed, but is there a better way to do this?
Matching balanced pairs using traditional regular expressions is difficult, if not impossible. Fortunately PCRE and others have an extension to match recursively, (?R)
will recursively match the entire pattern.
/\{(?R)*\}/
That says to match brace pairs which have zero or more brace pairs inside them. See perlretut->Recursive patterns and perlre->Extended Patterns->?R for more information.
Without recursion:
1 while s/\{\}//g;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With