Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Search for <n>th occurrence of regex

by repellent (Priest)
on Nov 05, 2008 at 20:02 UTC ( [id://721801]=CUFP: print w/replies, xml ) Need Help??

The following form searches for the <n>th occurence of a regex:
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?

Replies are listed 'Best First'.
Re: Search for <n>th occurrence of regex
by ikegami (Patriarch) on Nov 05, 2008 at 20:49 UTC
    As a corollary, if "abc" is placed before "\K", the substitution appends instead of replaces.
    # Appends to the 3rd occurence of 'abc' from start-of-line ($a = $ref) =~ s/^(?:.*?abc\K){3}/___/; print $a; # Appends to the 4th occurence of 'abc' from start-of-line ($a = $ref) =~ s/^(?:.*?abc\K){4}/___/; print $a; # omit ^ to append to every 2nd occurence of 'abc' ($a = $ref) =~ s/(?:.*?abc\K){2}/___/g; print $a; # omit ^ to append to every 1st occurence of 'abc' ($a = $ref) =~ s/(?:.*?abc\K){1}/___/g; print $a;

    Of course, the "{1}" is optional in the last pattern.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://721801]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2024-03-28 12:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found