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

Hi,

I have one string and its substring and would like to find which is the position of the words that match the substing. For instance, for the string:

this is a test

and the substing

is a test

I want to have as output the

2 3 4

Here is my code but is returs me the number of the first charachter.

my $str = "this is a test";</p> my $sub = "is a test"; if ($str =~ /\b$sub\b/) { print "match at char ",@-[0], "\n"; }

Any help would be useful.

Tahnks

Replies are listed 'Best First'.
Re: Find the position of substring
by hdb (Monsignor) on Apr 22, 2015 at 11:59 UTC

    Your result only depend on the number of words before your substring and the number of words in the substring:

    use strict; use warnings; my $string = 'this is a test'; my $substr = 'is a test'; if( $string =~ /(.*)\b$substr\b/ ) { # do we have a match? my $n = () = $1 =~ /\b(\w+)\b/g; # number of words before mat +ch my $m = () = $substr =~ /\b(\w+)\b/g; # number of words in match print join(' ',$n+1..$n+$m),"\n"; }
      Thanks! It works :)
Re: Find the position of substring
by Laurent_R (Canon) on Apr 22, 2015 at 17:59 UTC
    Rather than regexes, you could also use the index, split and substr built-ins, as shown in the following session under the debugger:
    DB<1> $str = "this is a test"; DB<2> $sub = "is a test"; DB<3> $index = index $str, $sub; DB<4> $nr_before = scalar split /\s+/, substr $str, 0, $index; DB<5> p $nr_before; 1 DB<6> $nr_in = scalar split /\s+/, $sub ; DB<7> p $nr_in; 3 DB<8> print ++$nr_before, " " for 1..$nr_in; 2 3 4
    Note: I know that the call to the scalar built-in is not really useful in a scalar context, but I thought it would clarify the idea.

    Je suis Charlie.