Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

by Eily (Monsignor)
on Jun 20, 2014 at 13:36 UTC ( [id://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 (Patriarch) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1090633]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-04-23 15:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found