开发者

Regex for finding number of times substring "hello hello" occurs in string "hello hello hello" [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago. 开发者_开发百科

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?


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


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


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜