Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PCRE regex to remove empty braces

Tags:

regex

perl

pcre

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?

like image 840
user5179929 Avatar asked Aug 01 '15 04:08

user5179929


2 Answers

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.

like image 146
Schwern Avatar answered Oct 31 '22 23:10

Schwern


Without recursion:

1 while s/\{\}//g;
like image 23
Borodin Avatar answered Oct 31 '22 22:10

Borodin