in reply to Re^2: Regex for replacing multiple nested matches
in thread Regex for replacing multiple nested matches
yieldsuse 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; }
@_ = ( '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 | |
|
Re^4: Regex for replacing multiple nested matches
by Lana (Beadle) on Sep 10, 2015 at 20:15 UTC |