我想要得到字符串中子字符串出现的次数。找到次数字符串“hello hello”的次数的正则表达式出现在字符串“hello hello hello”中
我的字符串是"hello hello hello"
。我想获得"hello hello"
发生在其中的次数,这在上述情况下是。
有人可以帮我找一个正则表达式吗?
我想要得到字符串中子字符串出现的次数。找到次数字符串“hello hello”的次数的正则表达式出现在字符串“hello hello hello”中
我的字符串是"hello hello hello"
。我想获得"hello hello"
发生在其中的次数,这在上述情况下是。
有人可以帮我找一个正则表达式吗?
根据要么你要计算(至极是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
尝试:
(?=hello hello)
使用先行可以让你找到重叠的结果。因为只有整个单词,你可以尝试:
\b(?=hello hello\b)
例子:http://rubular.com/r/om1xn1FmBI蓝色位置标记匹配
假设你的意思是“你好”,而不是“你好你好”,你只能分割你好。无需构造额外的正则表达式
$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
虽然这并不适用于重叠的子串。 – Thilo 2010-10-19 05:32:33
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
你是怎么** 3 **在你的例子中? – Kobi 2010-10-19 05:17:33
“3”怎么样? – codaddict 2010-10-19 05:18:07
你好新用户。我编辑了你的问题并将其清理了一下。我在里面保存了'3',如果是错误,请编辑它,如果不是,请解释它。谢谢,并欢迎堆栈溢出。 – Kobi 2010-10-19 05:26:13