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

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

Replies are listed 'Best First'.
Re^3: how to search and replace the match with specific number of times in a string
by Ratazong (Monsignor) on Jan 29, 2010 at 14:07 UTC
    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
Re^3: how to search and replace the match with specific number of times in a string
by Verillion (Initiate) on Jan 29, 2010 at 17:30 UTC

    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.