Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: search for nth occurrence of a pattern in a line

by ioannis (Vicar)
on May 17, 2006 at 08:56 UTC ( #549965=note: print w/ replies, xml ) Need Help??


in reply to search for nth occurrence of a pattern in a line

Here is a solution. The basic idea to count the times we of the found pattern as we scan the string from left to right. Although we can compact the code into 2 short lines, it is shown bellow longer and verbose.

# $n is the nth wanted occurence, as indicated by the question. # $i holds how many times we found the pattern my $str = ',n ,pple , d,y'; my ($n, $i) = 4; $str =~ / , # we are searching for the , pattern (?{ $i++}) # we found it again , increament $i /xgc # retain last occurance on failure for (1..$n); # print position in string print +($n == $i) ? pos($str) - 1 : 'not found';


Comment on Re: search for nth occurrence of a pattern in a line
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (10)
As of 2015-07-07 23:00 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