my $str = 'Fsih my test variable is fsihd or is it gfsih or gfsih +d fsih'; # 1111 2222 3333 + 4444 my $substr = 'fsih'; my $regexp = qr/\Q$substr\E/; my $replace = 'fish'; my $instance = 3; # 3rd print("$str\n"); scalar $str =~ /\G.*?$regexp/gc while --$instance; $str =~ s/\G(.*?)$regexp/$1$replace/; print("$str\n");
The /c is needed in case there are less than $instance instances of the search string.
In reply to Re^3: Replacing a specfied instance of a pattern in a string
by ikegami
in thread Replacing a specfied instance of a pattern in a string
by krisahoch
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |