Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

by vroom (Pope)
on Jan 18, 2000 at 23:44 UTC ( #2151=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 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"; } }

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2017-07-28 06:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I came, I saw, I ...
























    Results (424 votes). Check out past polls.