How to find every occurrence of a substring by a function?

J

Jürgen Exner

Peng Yu said:
Example 3b on the following page use a loop to find all substring.

http://perlmeme.org/howtos/perlfunc/index_function.html

I'm wondering if there is a function in perl library that can give me
back all the matches,

Maybe I misunderstand what you are looking for but it appears to me that
the g-modifier in list context does exactly what you want. From 'perldoc
perlretut':

In list context, "//g" returns a list of matched groupings, or
if there are no groupings, a list of matches to the whole
regexp.

jue
 
P

Peng Yu

Sure:

my @findall = $string =~ /pattern/g;

I think that I didn't make it clear. I want the location of the match.

For example, for the following variables, I want get an array that has
the number 0 and 7. You command gives an array of two same strings
'abc' and 'abc'.

$string="abcdefgabc";
$substring="abc";
 
J

John W. Krahn

Peng said:
I think that I didn't make it clear. I want the location of the match.

You said that you wanted something "just like findall" which according
to the page you referenced "Find all substrings where the RE matches,
and returns them as a list." which is exactly what the Perl code above does.

For example, for the following variables, I want get an array that has
the number 0 and 7. You command gives an array of two same strings
'abc' and 'abc'.

$string="abcdefgabc";
$substring="abc";

$ perl -le'
my $string = "abcdefgabc";
my $substring = "abc";
my @offsets;
{ use re "eval";
$string =~ /\Q$substring\E(??{ push @offsets, $-[ 0 ] })/g;
}
print "@offsets";
'
0 7




John
 
J

Jürgen Exner

Peng Yu said:
I think that I didn't make it clear. I want the location of the match.

You wrote: "give me back all the matches". That is different from the
location of those matches.

And according to the documentation your Python findall() appears to
return the found matches, too, not their positions:

findall() Find all substrings where the RE matches, and
returns them as a list

jue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,235
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top