Welcome to WebmasterWorld Guest from 54.163.168.15

Forum Moderators: coopster & jatar k & phranque

Determining how many times a string appears in a string

   
2:57 pm on Oct 30, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Is there a way to determine the number of instances a string appears in a larger string like here [javascript.internet.com], except in Perl, not JavaScript?
4:56 pm on Oct 30, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This should do it, even with regular expressions:

my $string = "substring substring substring oefiojoifasubstringioafesjvaiosubstring";
my $count = 0;
my $flag = 0;
do {
if ( $string =~ /substring/) {
$string = $';
$count++;
} else {
$flag = 1;
}
} until $flag == 1;

print "$count\n";

5:01 pm on Oct 30, 2004 (gmt 0)

10+ Year Member



This is answered in the Perl FAQ that ships with perl. Type this at the command line:

perldoc -q count

5:03 pm on Oct 30, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



"There's More Than One Way To Do It"
12:01 am on Nov 1, 2004 (gmt 0)

WebmasterWorld Senior Member kaled is a WebmasterWorld Top Contributor of All Time 10+ Year Member



I think something like this will work.

$tmp = $str;
$count = ($tmp ~= s/$search//g);

i.e. a global substitute with a null string.
I'm not certain the syntax above is correct - my perl is a bit rusty.

Kaled.

9:50 am on Nov 3, 2004 (gmt 0)

10+ Year Member



kaled has the right idea, but this syntax works:

my $count = ($string =~ tr/$substring//);
12:32 pm on Nov 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks everyone!
3:46 pm on Nov 4, 2004 (gmt 0)

WebmasterWorld Senior Member drdoc is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Here's yet another possibility:

$count = @{[$string =~ /$match/g]};

 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month