2010-10-19 57 views
1

我想要得到字符串中子字符串出现的次数。找到次数字符串“hello hello”的次数的正则表达式出现在字符串“hello hello hello”中

我的字符串是"hello hello hello"。我想获得"hello hello"发生在其中的次数,这在上述情况下是。
有人可以帮我找一个正则表达式吗?

+5

你是怎么** 3 **在你的例子中? – Kobi 2010-10-19 05:17:33

+0

“3”怎么样? – codaddict 2010-10-19 05:18:07

+0

你好新用户。我编辑了你的问题并将其清理了一下。我在里面保存了'3',如果是错误,请编辑它,如果不是,请解释它。谢谢,并欢迎堆栈溢出。 – Kobi 2010-10-19 05:26:13

回答

2

根据要么你要计算(至极是2),你可以做的hello发生(这是3在你的例子)或hello hello数量:

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

尝试:

(?=hello hello) 

使用先行可以让你找到重叠的结果。因为只有整个单词,你可以尝试:

\b(?=hello hello\b) 

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

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 
+1

现在,我不是perl的家伙,但不是'/ hello /'正则表达式?在这种情况下,你可能会和它相匹配。另外,请注意,问题问''你好你好'',这表明重叠匹配。 – Kobi 2010-10-19 05:29:16

+0

请注意,/ hello /是一个正则表达式,但:-) – Thilo 2010-10-19 05:30:01

+0

@Kobi:+1。虽然拆分可能没有正则表达式,但重叠会成为一个问题。 – Thilo 2010-10-19 05:32:14

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 
+1

为什么在空间上分裂? – Thilo 2010-10-19 05:34:04

+0

提供了更多的“通用解决方案”,即首先将字符串分解为单词,然后通过“grep”检查它是否需要单词。 – 2010-10-19 05:37:42

+1

假设只需要对词边界进行匹配就更一般了吗? (特别是因为“你好,你好”不是一个字) – Thilo 2010-10-19 05:39:32