Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: positions of all occurrences of a substring in a string

by Eily (Curate)
on Jun 20, 2014 at 13:36 UTC ( #1090633=note: print w/ replies, xml ) Need Help??


in reply to positions of all occurrences of a substring in a string

Using substring and iterating over the string seems simple enough, and it would work alright.

If you want to use a regex, you should use look ahead assertions if you want to find occurrences that can overlap (and for pos to give you the start of the match). :

perl -E 'for("bababa") { say pos while /(?=baba)/g }' 0 2

If you don't want to find overlapping occurrences, you can use @- to find the start of the last match.

perl -E 'for("bababa") { say $-[0] while /baba/g }' 0


Comment on Re: positions of all occurrences of a substring in a string
Select or Download Code
Replies are listed 'Best First'.
Re^2: positions of all occurrences of a substring in a string
by ikegami (Pope) on Jun 20, 2014 at 18:43 UTC
    ($-[0] will work in the former too.)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (12)
As of 2015-07-28 09:45 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 (254 votes), past polls