Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

( #2151=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How do I find the Nth occurrence of a pattern? contributed by vroom

Use the /g (global) to find all occurrences in a string. Place the matching statement within a while loop and count until you get to the wanted number.
$n=5; #want the 5th occurrence of a group of 5 numbers $count=0; while(/(\d{5})/g){ if(++$count==$n){ print "The $n\th occurrence was $1\n"; } }

Comment on Answer: How do I find the Nth occurrence of a pattern?
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (13)
As of 2015-07-07 22:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls