如何在Perl字串中計算匹配項的數量?


在Perl中,我們可以透過不同的方法找到字串中匹配項的數量。在本教程中,我們將討論三種最常用的方法。

在Perl字串中搜索單個字元

首先,讓我們考慮一下在字串中搜索單個字元模式的情況。例如,假設我們有一個類似於這樣的字串:

"India.Japan.Russia.USA.China" 

並且,我們想找到“.”(點)在上述字串中出現的次數。

示例

考慮以下程式碼。

my $countries = "India.Japan.Russia.USA.China";
print "The given string is: ", $countries;
print "\n";
my @countDotOccurrences = $countries =~ /\./g;
print "Number of dots in the string: ", scalar @countDotOccurrences;

輸出

如果您在線上Perl編譯器中執行上述程式碼,您將在終端中獲得以下輸出

The given string is: India.Japan.Russia.USA.China
Number of dots in the string: 4

示例

現在讓我們採用另一種方法,它也可以讓我們找到Perl字串中單個字元的出現次數。考慮以下程式碼。

$someString = "Perl Codes Can Be Difficult To Read";
print "The given string is: ", $someString;
print "\n";
$countT = ($someString =~ tr/T//);
$countX = ($someString =~ tr/X//);
print "$countT T characters in the string\n";
print "$countX X characters in the string";

輸出

如果您在Perl編譯器中執行上述程式碼,您將在終端中獲得以下輸出

The given string is: Perl Codes Can Be Difficult To Read
1 T characters in the string
0 X characters in the string

如輸出所示,給定字串有1個“T”和0個“X”字元。請注意,我們只搜尋大寫字母。

在Perl字串中搜索多個字元

在以上兩個例子中,我們探討了在字串中查詢單個字元出現次數的情況。在這個例子中,我們將探討如何搜尋多個字元。

示例

考慮以下程式碼。這裡,我們有一個包含一些正數和負數的字串。我們將找出給定字串中有多少個負數。

$someString = "-9 57 48 -2 -33 -76 4 13 -44";
print "The given string is: ", $someString;
print "\n";
while ($someString =~ /-\d+/g) {
   $negativeCount++
}
print "There are $negativeCount negative numbers in the string.";

輸出

如果您在線上Perl編譯器中執行上述程式碼,您將在終端中獲得以下輸出

The given string is: -9 57 48 -2 -33 -76 4 13 -44
There are 5 negative numbers in the string.

結論

在本教程中,我們使用了多個示例來演示如何計算Perl字串中匹配項的數量。

更新於:2023年4月4日

1K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告