7

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?

  • 4
    Matching balanced pairs is one of the most difficult regex problems. Fortunately, PCRE has an extension to deal with it. This answer might help. https://stackoverflow.com/questions/5410652/regex-delete-contents-of-square-brackets – Schwern Aug 01 '15 at 04:55

2 Answers2

10

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.

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
Schwern
  • 153,029
  • 25
  • 195
  • 336
2

Without recursion:

1 while s/\{\}//g;
Borodin
  • 126,100
  • 9
  • 70
  • 144