2010-10-19 55 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