in reply to Re^2: 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

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/

Replies are listed 'Best First'.
Re^4: how to search and replace the match with specific number of times in a string
by markkawika (Monk) on Jan 29, 2010 at 19:26 UTC
    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.