The following form searches for the <n>th occurence of a regex:
/^(?:.*?\Kregex){<n>}/
This is based on a regex I discovered during my Vim hacking days.
Vim regex provides the atom
\zs to set the start of a regex match. It wasn't until recent Perl 5.10+ that the
\K construct was introduced.
# only Perl 5.10+
my $a;
my $ref = "abc x abc y abc z abc\n";
# search 3rd occurence of 'abc' from start-of-line
($a = $ref) =~ s/^(?:.*?\Kabc){3}/___/;
print $a;
# search 4th occurence of 'abc' from start-of-line
($a = $ref) =~ s/^(?:.*?\Kabc){4}/___/;
print $a;
# omit ^ to search every 2nd occurence of 'abc'
($a = $ref) =~ s/(?:.*?\Kabc){2}/___/g;
print $a;
# omit ^ to search every 1st occurence of 'abc'
($a = $ref) =~ s/(?:.*?\Kabc){1}/___/g;
print $a;
__END__
abc x abc y ___ z abc
abc x abc y abc z ___
abc x ___ y abc z ___
___ x ___ y ___ z ___
If appropriate, this could be added as an update to:
How do I change the Nth occurrence of something?