PCRE regular expression to remove empty curly braces

How to write a regular expression to remove all pairs of curly braces that contain nothing?

For example, {} and {{}} should be reduced to an empty line, but {{} will become { and {{A}{}} become {{A}} .

I am currently executing s/\{\}//g in a loop until the length of the string is fixed, but is there a better way to do this?

+7
regex perl pcre
source share
2 answers

Matching balanced pairs using traditional regular expressions is difficult, if not impossible. Fortunately, PCRE and others have the extension to fit recursively, (?R) will fit the entire pattern recursively.

 /\{(?R)*\}/ 

This suggests that you need to match pairs of curly braces that have zero or more pairs of curly braces in them. See perlretut-> Fractal Templates and perlre-> Advanced Templates →? R for more information.

+10
source share

Without recursion:

 1 while s/\{\}//g; 
+2
source share

All Articles