计算Perl中字符串中单词的出现次数

时间:2015-06-16 20:32:37

标签: regex perl

我试图找出“The / the”的出现次数。下面是我试过的代码“

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

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

$scalar=@splitarr;
print $scalar;

字符串是:

  

你好,你是如何想要在这个项目上工作但我是你的   在

它给出的输出是7.但是使用字符串:

  

你好,你是如何想要在这个项目上工作但我是你的

输出为5.我怀疑我的正则表达式。任何人都可以帮助指出什么是错的。

4 个答案:

答案 0 :(得分: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 :(得分: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)。

答案 2 :(得分:1)

以下代码段使用代码副作用来递增计数器,然后是始终失败的匹配以继续搜索。它为重叠的匹配产生正确的答案(例如&#34; aaaa&#34;包含&#34; aa&#34; 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";

答案 3 :(得分:0)

你需要的是&#39; countof&#39;运算符来计算匹配数:

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;
相关问题