Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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

by Eily (Deacon)
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 about the Monastery: (11)
As of 2014-12-28 19:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (182 votes), past polls