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

If replacing doesn't create a new possible match, you could do:
$string =~ s/a/i/ for 1 .. $N;
Or, in the rare case searching from the beginning over and over again is expensive, or if a replace could create a new match:
my $count = 0; $string =~ s/a(??{++ $count <= $N ? "(*ACCEPT)" : "(*FAIL)"})/i/g; # Use '""' instead of '(*ACCEPT)' and '(?!)' instead of '(*FAIL)' on o +ld Perls.

Replies are listed 'Best First'.
Re^2: how to search and replace the match with specific number of times in a string
by AnomalousMonk (Archbishop) on Jan 29, 2010 at 18:00 UTC

    Note that there is a warning (at least as of the current documentation) that the  (*ACCEPT) backtracking control verb is "... highly experimental [and] is not recommended for production code."

    A slightly different take:

    >perl -wMstrict -le "my $N = 3; my $string = 'XXXXXaXXbXXXc'; $string =~ s{ X (?(?{ $N and $N-- }) | (*FAIL)) }{Xy}xmsg; print $string; " XyXyXyXXaXXbXXXc

    See Special Backtracking Control Verbs in perlre.