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?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.