查找字符串“hello hello”的正则表达式出现在字符串“hello hello hello”中

时间:2010-10-19 05:12:35

标签: regex perl

我想得到字符串中子字符串的出现次数。

我的字符串是"hello hello hello"。我希望得到"hello hello"出现的次数,在上面的例子中 2
有人可以帮我找一个正则表达式吗?

5 个答案:

答案 0 :(得分:2)

尝试:

(?=hello hello)

使用前瞻功能可以找到重叠的结果。仅限全文,您可以尝试:

\b(?=hello hello\b)

示例:http://rubular.com/r/om1xn1FmBI 蓝色位置标记匹配

答案 1 :(得分:2)

根据您要计算hello(在您的示例中为3)或hello hello(2为2)的出现次数,您可以执行以下操作:

#!/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

答案 2 :(得分:1)

假设你的意思是“你好”而不是“你好你好”,你可以分开打招呼。无需构建额外的正则表达式

$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

答案 3 :(得分:1)

答案 4 :(得分:0)

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