in reply to how to search and replace the match with specific number of times in a string

Simplest would be to use a looping statement modifier.

$ perl -E ' > $str = q{abcabdaaa}; > say $str; > $str =~ s{a}{i} for 1 .. 3; > say $str;' abcabdaaa ibcibdiaa $

I hope this is helpful.

Cheers,

JohnGG

  • Comment on Re: how to search and replace the match with specific number of times in a string
  • Download Code

Replies are listed 'Best First'.
Re^2: how to search and replace the match with specific number of times in a string
by JavaFan (Canon) on Jan 29, 2010 at 11:09 UTC
    Note that doesn't work in the general case. For instance, suppose you want to replace first three sequences of whitespace with a single space.
    s/\s+/ / for 1 .. 3;
    would replace the first sequence three times.
Re^2: how to search and replace the match with specific number of times in a string
by loki (Novice) on Jan 29, 2010 at 13:47 UTC
    hi but am facing problem when am replacing by
    $s="***ab***c"; $s=~s{\*}{\*\n} for 1..2; print$s;

    it replaces first * by *\n and the rest it ignores... why can any one explain me pls?

    my output was: * **ab***c
    but desired was
    * * *ab***c

      I believe you can get the function to work expanding the regex a little bit.

      $s = "***ab***c"; $s =~ s/\*([^\n])/\*\n\1/ for 1 .. 2; print $s;

      Output was:

      * * *ab***c

      Since you know the state it's going to be after it's changed, you can include that in the regex. Hence *, not followed by \n will match, along with the for loop suggested earlier, gives you your count. Using \1 here just puts the next value (after the matched *) back into the string.

      Update: markkawika's comment might be below threshold, so I'll add it here as well, since his regex is better than mine. Suggested regex: s/\*(?!\n)/*\n/

        That's one way, but I think a negative look-ahead would serve you better in this specific case:
        $s =~ s/\*(?!\n)/*\n/;
        Also, you don't need to escape the * in the replacement string.
      your code does 2 replaces:
      1. * will be replaced by *\n => so your string is    *\n*ab***c
      2. again, the first * will be replaced by *\n, giving you    *\n\n*ab***c
      If you want to continue your approach, a solution could be:
      1. replace * by some string not containing your search-pattern (e.g. X) $s=~s{\*}{X} for 1..2;
      2. replace the new string by your search-pattern $s=~s{X}{\*\n} for 1..2;

      Or follow some other advice given in this thread...

      HTH, Rata