How to find the next unbalanced bracket?

The regular expression below displays everything until the last balanced } .

Now, what regular expression can capture everything until the next unbalanced } ? In other words, how can I get ... {three {four}} five} from $str instead of just ... {three {four}} ?

 my $str = "one two {three {four}} five} six"; if ( $str =~ / ( .*? { (?> [^{}] | (?-1) )+ } ) /sx ) { print "$1\n"; } 
+4
source share
1 answer

So you want to combine

 [noncurlies [block noncurlies [...]]] "}" 

where a block is

 "{" [noncurlies [block noncurlies [...]]] "}" 

Like a grammar:

 start : text "}" text : noncurly* ( block noncurly* )* block : "{" text "}" noncurly : /[^{}]/ 

As a regular expression (5.10 +):

 / ^ ( ( [^{}]* (?: \{ (?-1) \} [^{}]* )* ) \} ) /x 

As a regular expression (5.10 +):

 / ^ ( (?&TEXT) \} ) (?(DEFINE) (?<TEXT> [^{}]* (?: (?&BLOCK) [^{}]* )* ) (?<BLOCK> \{ (?&TEXT) \} ) ) /x 
+3
source

All Articles