in reply to Re^2: Regex for replacing multiple nested matches
in thread Regex for replacing multiple nested matches

You don't need to escape the } within a bracketed character class. You do need not to accept any opening { within your bracketed character class.
use Data::Dumper; my $string = 'some text ###RAND{1a|###RAND{2a|2b|2c|###RAND{3a|3b|3c|3 +d}|2d}|1b|1c|1d} some text'; print process_rands($string)."\n"; sub process_rands { my $sentence = shift; while (1) { last unless $sentence =~ s!###RAND\{([^{}]+)\}!get_rand_arr_ +el($1)!e; print $sentence."\n"; } return $sentence; } sub get_rand_arr_el { warn Data::Dumper->Dump([\@_],[qw(*_)]),' '; my @array = split '\|',$_[0]; my $randomelement = $array[ rand @array ]; return $randomelement; }
yields
@_ = ( '3a|3b|3c|3d' ); at play.pl line 18. some text ###RAND{1a|###RAND{2a|2b|2c|3c|2d}|1b|1c|1d} some text @_ = ( '2a|2b|2c|3c|2d' ); at play.pl line 18. some text ###RAND{1a|2b|1b|1c|1d} some text @_ = ( '1a|2b|1b|1c|1d' ); at play.pl line 18. some text 1d some text some text 1d some text

Replies are listed 'Best First'.
Re^4: Regex for replacing multiple nested matches
by AnomalousMonk (Archbishop) on Sep 10, 2015 at 21:35 UTC
    while (1) { last unless $sentence =~ s!###RAND\{([^{}]+)\}!get_rand_arr_el($1)!e +; print $sentence."\n"; }

    The  while (1) { last unless ... } loop is more concise and clear and IMHO better if written
        1 while $sentence =~ s!###RAND\{([^{}]+)\}!get_rand_arr_el($1)!eg;
    Just replace the  1 with  print $sentence."\n" if the debug print is needed.

    Also: Use of the  /g modifier with the  s/// substitution allows killing multiple birds (substitutions) with one stone (loop pass).

    Update: Also: Lana: Be sure to test all this thoroughly. Otherwise, you may end up having even more trouble with the planets!


    Give a man a fish:  <%-{-{-{-<

Re^4: Regex for replacing multiple nested matches
by Lana (Beadle) on Sep 10, 2015 at 20:15 UTC

    Oh my! Now I see what you mean :) There's really something wrong with planets today!

    I didn't take from the first time because you offered slightly different way, but I was stuck with catching the last match occurence, because I need it to work in one more part of my other script.