tags:

views:

135

answers:

6

I want to get the count of occurrence of a substring within a string.

My string is "hello hello hello". I want to get the number of times "hello hello" occurs in it, which in the above case is 2.
Can someone please help me find a regex for it?

+2  A: 

Try:

(?=hello hello)

Using a lookahead lets you find overlapping results. For whole word only, you may try:

\b(?=hello hello\b)

Example: http://rubular.com/r/om1xn1FmBI the blue positions mark a match

Kobi
+1  A: 

Assuming you meant "hello" and not "hello hello" , you can just split on hello. No need to construct extra regex

$string="hello hello blah hello blah helloworld hello blah blah hello";
@s = split "hello", $string, -1;
print scalar @s - 1 ."\n"; #get size of array
ghostdog74
Now, I'm no perl guy, but isn't `/hello/` a regex? In that case, you might as well match against it. Also, note that the question asks about `"hello hello"`, which suggests overlapping matches.
Kobi
Note that /hello/ is a regex, though :-)
Thilo
@Kobi: +1. While split can probably be done without a regex, overlapping would be a problem.
Thilo
and note that question also says 3. Unless the OP redefines that, whether is overlapping or not is pure guess work
ghostdog74
That is correct `:)`
Kobi
+1  A: 

This is what you are looking for actually, Counting the occurrences of a substring - the fastest way.

Vantomex
That does not work for overlapping substrings though.
Thilo
A: 
use strict;
use warning;
my $str = "hello hello hello bla bla hello bla hello";
my $count = grep /hello/ , split /\s+/,$str ;
print"$count"; #output 5
Nikhil Jain
why split on space?
Thilo
providing more `general solution` ie., first by splittig the string into words and then check by `grep` whether it is required word or not.
Nikhil Jain
how is assuming that matching only needs to be done on word boundaries more general? (especially since "hello hello" is not one word)
Thilo
yes that's true, but i am considering "hello" as one word unless OP explain it more and split string into words because assuming that string may contain words other than "hello".
Nikhil Jain
+3  A: 

Depending on either you want to count the number of occurrence of hello (which is 3 in your example) or hello hello (wich is 2), you can do:

#!/usr/bin/perl 
use 5.10.1;
use warnings;
use strict;

my $str = q/hello hello hello/;
my $count1 =()= $str =~ /(?=\bhello hello\b)/g;
say $count1;  # gives 2

my $count2 =()= $str =~ /\bhello\b/g;
say $count2;  # gives 3
M42
A: 

Thank you all so much! I meant 2 that was a typo! Sorry for that! Thanks again!

Radz
Very well, and you could consider to accept an answer.
M42