Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: regex for nested "<"/">'

by clueless newbie (Curate)
on Feb 12, 2020 at 15:12 UTC ( [id://11112868] : note . print w/replies, xml ) Need Help??


in reply to regex for nested "<"/">'

Replies are listed 'Best First'.
Re^2: regex for nested "<"/">'
by jo37 (Deacon) on Feb 12, 2020 at 21:42 UTC
    For balanced begin/end matching, this might do:
    $re = qr{ ( (?: (?&OPEN) (?: (?>(?:.*?(?=(?&OPEN)|(?&CLOSE)))) | (?-1) )* (?&CLOSE) ) ) (?(DEFINE) (?<OPEN>\bBEGIN\b) (?<CLOSE>\bEND\b) )}x;

      You're my hero!

      Now to figure out exactly how it works!

Re^2: regex for nested "<"/">'
by tybalt89 (Monsignor) on Feb 13, 2020 at 17:00 UTC
    #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11112811 use warnings; my $input = <<ENDOFSTRING; beginning a bend before stuff begin one begin three end five end after stuff beginning a bend ENDOFSTRING print $input, '-' x 70, "\n"; my $level = 0; my $nested = $input =~ s/(\bbegin\b)|(\bend\b)|./ ( $1 && $level++, $level ? $& : '', $2 && $level--)[1] /gesr; print "$nested\n";

    Outputs:

    beginning a bend before stuff begin one begin three end five end after stuff beginning a bend ---------------------------------------------------------------------- begin one begin three end five end