Is there a command or package to search for all instances of asubstring in a string?

P

Peng Yu

Hi,

Can somebody let me know if there is a command or function to find all
the occurance of a substring in a string? I can write a program to do
this. I just want to know what is the best way to do this.

Thanks,
Peng
 
J

John W. Krahn

Peng said:
Can somebody let me know if there is a command or function to find all
the occurance of a substring in a string? I can write a program to do
this. I just want to know what is the best way to do this.

perldoc -f m
perldoc -f index
perldoc -f rindex


John
 
T

Tad J McClellan

Peng Yu said:
Can somebody let me know if there is a command or function to find all
the occurance of a substring in a string?


What does "find" mean when you say it?

If string="aaa" and substring="aa", should it "find" the substring 1 or 2 times?

I just want to know what is the best way to do this.


That depends entirely on what "this" is...

If "this" is:

find all of the starting indexes of a substring in a larger string

then to find non-overlapping substrings:

push @indexes, pos($string) - length $substr, while $string =~ /$substr/g;

or to find overlapping substrings:

for (my $pos = -1;;) {
$pos = index $string, $substr, $pos+1;
last if $pos == -1;
push @indexes, $pos;
}
 
J

Jürgen Exner

Peng Yu said:
Can somebody let me know if there is a command or function to find all
the occurance of a substring in a string? I can write a program to do
this. I just want to know what is the best way to do this.

perldoc -f index

and keep looking ( aka looping)

jue
 
I

Ilya Zakharevich

[A complimentary Cc of this posting was sent to
Tad J McClellan
find all of the starting indexes of a substring in a larger string

then to find non-overlapping substrings:

push @indexes, pos($string) - length $substr, while $string =~ /$substr/g;

One should keep in mind that overlapping substrings can be done in the
same way:

push @indexes, pos($string) - length $substr, while $string =~ /(?=$substr)/g;

# As above, $substr should not contain metachars; otherwise \Q\E may
be needed...

Hope this helps,
Ilya
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top