我想要得到字符串中子字符串出現的次數。找到次數字符串「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