in reply to Re: looking for a regex
in thread looking for a regex

Thanks. A neat trick By substituting a variable I meant:
@sub=('men','boy','girl'); $s ='25 {fred and barney} text 2.36 12.0 {bam bam} text {pebbles}';
end result
$s ='25 {men} text 2.36 12.0 {boy} text {girl}';
I know I can do this by splitting, substituting and rejoining, but I though there may be a more elegant way.

Replies are listed 'Best First'.
Re: Re: Re: looking for a regex
by BrowserUk (Patriarch) on Apr 22, 2003 at 10:50 UTC

    Provided you know you have enough values in @sub to match the pairs of curlies

    $s ='25 {fred and barney} text 2.36 12.0 {bam bam} text {pebbles}'; $n=0; $s =~ s_\{.*?\}_{$sub[$n++]}_g; print $s; 25 {men} text 2.36 12.0 {boy} text {girl}

    I'm not at all sure about using _ as the delimiter, but everything else I tried was altogether too messy.


    Examine what is said, not who speaks.
    1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
    2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
    3) Any sufficiently advanced technology is indistinguishable from magic.
    Arthur C. Clarke.

      I'm not at all sure about using _ as the delimiter, but everything else I tried was altogether too messy.

      Just so you know, they curlies dont need to be escaped here. And this in turn means the traditional regex delimiter looks fine

      s/{.*?}/{$sub[$n++]}/g;

      As the open curlie starts at the BOS it _can't_ have its meta meaning, and thus needs no escape. Dont worry, as I found out ages ago, perl is quite smart about delimiters in regexes. For instance

      s{{.*?}}{{$sub[$n++]}}g;

      also works just fine, even if it looks a mess.

      Anyway, just my $0.02
      ---
      demerphq

      <Elian> And I do take a kind of perverse pleasure in having an OO assembly language...

      Tahnks this does what I want very neatly!!