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?
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?
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
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
This is what you are looking for actually, Counting the occurrences of a substring - the fastest way.
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
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