如何在Perl字符串中计算匹配项的数量?


在Perl中,我们可以通过不同的方法找到字符串中匹配项的数量。在本教程中,我们将讨论三种最常用的方法。

在Perl字符串中搜索单个字符

首先,让我们考虑一下在字符串中搜索单个字符模式的情况。例如,假设我们有一个类似于这样的字符串:

"India.Japan.Russia.USA.China" 

并且,我们想找到“.”(点)在上述字符串中出现的次数。

示例

考虑以下代码。

Open Compiler
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字符串中单个字符的出现次数。考虑以下代码。

Open Compiler
$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字符串中搜索多个字符

在以上两个例子中,我们探讨了在字符串中查找单个字符出现次数的情况。在这个例子中,我们将探讨如何搜索多个字符。

示例

考虑以下代码。这里,我们有一个包含一些正数和负数的字符串。我们将找出给定字符串中有多少个负数。

Open Compiler
$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.

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

在本教程中,我们使用了多个示例来演示如何计算Perl字符串中匹配项的数量。

更新于:2023年4月4日

1K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告