Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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

by Eily (Chaplain)
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
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 having an uproarious good time at the Monastery: (12)
As of 2014-10-21 19:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (107 votes), past polls