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

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

by Eily (Priest)
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

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 perusing the Monastery: (6)
As of 2016-09-28 21:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (540 votes). Check out past polls.