2015-06-16 39 views
0

字符串我試圖找出「的/在」出現的次數。下面是我嘗試」計數出現在Perl中

print ("Enter the String.\n"); 
$inputline = <STDIN>; 
chop($inputline); 
$regex="\[Tt\]he"; 
if($inputline ne "") 
{ 

@splitarr= split(/$regex/,$inputline); 
} 

[email protected]; 
print $scalar; 

的字符串是代碼:

你好我的U的 的

輸出你怎麼樣對項目的想工作,但它給出的是7.然而與字符串:

你好你是如何工作的e項目,但我ü

輸出是5.我懷疑我的正則表達式。任何人都可以幫助指出什麼是錯的。

+0

有5個''字樣,你應該使用匹配而不是分割 – MaxZoom

+0

你應該得到第一個7,第二個6。嘗試使用'print @ splitter'或更好地使用Data :: Dumper。 – sln

回答

2

我得到正確的數量 - 6 - 第一個字符串

但是你的方法是錯誤的,因爲如果算上件的數量,您通過分裂Ø得到在正則表達式模式下,它會根據字是否出現在字符串的開始處而給出不同的值。你也應該把單詞邊界\b到你的正則表達式,以防止正則表達式的匹配類似theory

而且,不需要逃避方括號,並且可以使用/i修改做的情況下,獨立的比賽

嘗試這樣的事情,而不是

use strict; 
use warnings; 

print 'Enter the String: '; 
my $inputline = <>; 
chomp $inputline; 

my $regex = 'the'; 

if ($inputline ne '') { 
    my @matches = $inputline =~ /\b$regex\b/gi; 
    print scalar @matches, " occurrences\n"; 
} 
1

隨着split,你正在計算中的之間的子字符串。使用匹配,而不是:

#!/usr/bin/perl 
use warnings; 
use strict; 

my $regex = qr/[Tt]he/; 

for my $string ('Hello the how are you the wanna work on the project but i the u the The', 
       'Hello the how are you the wanna work on the project but i the u the', 
       'the theological cathedral' 
       ) { 
    my $count =() = $string =~ /$regex/g; 
    print $count, "\n"; 

    my @between = split /$regex/, $string; 
    print 0 + @between, "\n"; 

    print join '|', @between; 
    print "\n"; 
} 

注意,這兩種方法返回你提到的兩個輸入相同數量(和第一個返回6,不7)。

0

你需要的是「countof」操作數匹配的數量:

my $string = "Hello the how are you the wanna work on the project but i the u the The"; 
my $count =() = $string =~/[Tt]he/g; 
print $count; 

如果您想選擇只有兩個字theThe,添加單詞邊界:

my $string = "Hello the how are you the wanna work on the project but i the u the The"; 
my $count =() = $string =~/\b[Tt]he\b/g; 
print $count; 
+0

感謝您的所有答案。它讓我對自己在做什麼有了深刻的瞭解。我學到了很多。 :) –

1

下面的代碼片斷使用代碼副作用遞增計數器,其次是一個始終沒有比賽繼續尋找。它爲重疊的匹配產生正確答案(例如,「aaaa」包含「aa」3次,而不是2)。基於拆分的答案沒有得到正確的答案。

my $i; 
my $string; 

$i = 0; 
$string = "aaaa"; 
$string =~ /aa(?{$i++})(?!)/; 
print "'$string' contains /aa/ x $i (should be 3)\n"; 

$i = 0; 
$string = "Hello the how are you the wanna work on the project but i the u the The"; 
$string =~ /[tT]he(?{$i++})(?!)/; 
print "'$string' contains /[tT]he/ x $i (should be 6)\n"; 

$i = 0; 
$string = "Hello the how are you the wanna work on the project but i the u the"; 
$string =~ /[tT]he(?{$i++})(?!)/; 
print "'$string' contains /[tT]he/ x $i (should be 5)\n";