carolw has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

Should I loop over index to find the positions of all occurences of a substring in a string or is there a function that can retrieve the positions of all occurences?

Thanks

Carol

  • Comment on positions of all occurrences of a substring in a string

Replies are listed 'Best First'.
Re: positions of all occurrences of a substring in a string
by LanX (Saint) on Jun 20, 2014 at 13:12 UTC
    You still need to loop but its easier written with pos and looping over a regex with /g modifier.

    Something like:

     print pos while /substr/g ¹

    edit

    Though you might need to subtract the length of the match if you need the start position.

    Of course TIMTOWTDI. :)

    update

    ¹) corrected for to while

    test:

    DB<107> $_='abcd'x4 => "abcdabcdabcdabcd" DB<108> print pos()-2 while m/ab/g 04812

    Cheers Rolf

    (addicted to the Perl Programming Language)

Re: positions of all occurrences of a substring in a string
by Eily (Monsignor) on Jun 20, 2014 at 13:36 UTC

    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

      ($-[0] will work in the former too.)
Re: positions of all occurrences of a substring in a string
by vinoth.ree (Monsignor) on Jun 20, 2014 at 13:32 UTC

    Hi,

    Yes, You need to loop over index() function to find every occurrence of a substring in a string.

    Example:

    #!/usr/bin/perl use strict; use warnings; my $string = 'every occurrence of a substring in a string'; my $char = 'st'; my $offset = 0; my $result = index($string, $char, $offset); while ($result != -1) { print "Found $char at $result\n"; $offset = $result + 1; $result = index($string, $char, $offset); }

    The above code finds the substring 'st' in the string.

    Output:

    Found st at 25

    Found st at 37


    All is well
      my @poss; my $pos = -1; while (($pos = index($string, $char, $pos + 1)) != -1) { push @poss, $pos; }
Re: positions of all occurrences of a substring in a string
by InfiniteSilence (Curate) on Jun 20, 2014 at 13:35 UTC

    Read perldoc perlvar. pos gives you the last position of the match. Instead:

    perl -e '$str = q|aaabbbcccddd|; while($str=~m/(\S)\1\1/g){print @-[0] +};' 0369

    Celebrate Intellectual Diversity

A reply falls below the community's threshold of quality. You may see it by logging in.
A reply falls below the community's threshold of quality. You may see it by logging in.