in reply to Re: Replacing with null
in thread Replacing with null
Here's a more general approach using 5.10's \K assertion. The {n} quantifier (where n could be $n) allows any occurrence to be replaced.
>perl -wMstrict -le "my $s = 'Foo|Fate|||Fate||||Pre|Fate|Post|||||Alive|Alive'; my $Fate = qr{ Fate }xms; my $not_Fate = qr{ (?! $Fate) . }xms; $s =~ s{ (?: $Fate $not_Fate*){2} \K $Fate }{}xms; print $s; " Foo|Fate|||Fate||||Pre||Post|||||Alive|Alive
Update: Here's a general approach based on split, but I doubt it will be significantly faster (if at all) than the regex approach. Works only for positive values of $n.
>perl -wMstrict -le "my $s = 'Foo|1ate|||2ate||||Pre|3ate|Post|||||4ate|Alive'; my $Fate = qr{ \d ate }xms; my $n = shift; my $x = 2 * $n; $s = join '', grep defined, (split /($Fate)/, $s, $n + 1)[0 .. $x - 2, $x] ; print qq{'$s'}; " 3 'Foo|1ate|||2ate||||Pre||Post|||||4ate|Alive'
|
|---|