Hi Monks!

First of all, sorry for the kind of dumb question, but I stuck with it. Maybe there something wrong with planet positions in the sky today. :) (jk)

Well, here is a code:

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; my $count = () = $sentence =~ /###RAND/g; for (1..$count){ $sentence =~ s!.*###RAND\{([^\}]+)\}!get_rand_arr_el(sp +lit(/\|/,$1))!eg; print $sentence."\n"; } return $sentence; } sub get_rand_arr_el { my @array = @_; my $randomelement = $array[ rand @array ]; return $randomelement; }

The $string contains three text arrays like ###RAND{a|b|c|d} nested into each other. The a-b-c-d is a text array splitted by a pipe. What I need is process all occurences of the ###RAND{a|b|c|d} arrays in $count passes starting from the last one and moving to the first - to avoid interfering ###RAND{a|b|c|d} vars. Each pass must substitute ###RAND{a|b|c|d} with random element from the a|b|c|d array. As in this example there three nested ###RAND{a|b|c|d} text arrays, the steps should look like this:

some text ###RAND{1a|###RAND{2a|2b|2c|###RAND{3a|3b|3c|3d}|2d}|1b|1c|1 +d} some text some text ###RAND{1a|###RAND{2a|2b|2c|3b|2d}|1b|1c|1d} some text some text ###RAND{1a|2d|1b|1c|1d} some text some text 1c some text

How to make the regexp to substitute only the last occurence in each pass?

Thank you!
Lana

In reply to Regex for replacing multiple nested matches by Lana

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.