Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Answer: How do I find the Nth occurrence of a pattern?

by Roy Johnson (Monsignor)
on Oct 28, 2003 at 20:53 UTC ( #302814=categorized answer: print w/replies, xml ) Need Help??

Q&A > regular expressions > How do I find the Nth occurrence of a pattern? - Answer contributed by Roy Johnson

A recent discussion found this to be the fastest way, and it's pretty slick:
$_='abcabbcabbbbcabcabbcab'; my $n = 3; ## Find the $nth occurrence my $pat = qr/ab+/; ## of this pattern my ($NthMatch) = /(?:.*?($pat)){$n}/; print "Match #$n looks like $NthMatch\n";
The regex is: find the pattern (optionally preceded by something that isn't the pattern) n times. The pattern is in parens, so the final match will be returned.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
[Discipulus]: New Zeland and Italy share a simila faith!
[Discipulus]: same shape, earthquakes and premier dimissions the same day

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2016-12-05 11:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (80 votes). Check out past polls.