【问题标题】:Count the number of non-whitespace characters in a string in Perl [duplicate]计算Perl中字符串中非空白字符的数量[重复]
【发布时间】:2021-05-28 06:03:49
【问题描述】:

我试图弄清楚如何计算字符串中的所有非空白字符,这样在下面的示例中我会得到 4 的输出。

my $str = 'A b C $'; 

my $cnt =~ /\S/g;  

print "Char Count: $cnt\n";

这个Is there a Perl shortcut to count the number of matches in a string? 没有回答我的问题。

perl -e 'my $str = "A b C"; my $cnt = () = $str =~ /\./gi;  print "Chs: $cnt\n";'
Chs: 0

有人一直想说这个问题是这个问题的重复:Is there a Perl shortcut to count the number of matches in a string?

但是,另一个问题提到了如何匹配特定字符,在他们的情况下,我相信它是一个点。我查看了许多其他试图匹配特定字符的示例,但无法让它们匹配除空格以外的所有字符。

这没有回答我的问题。

$string = "ThisXlineXhasXsomeXx'sXinXit";
$count = ($string =~ tr/X//);
print "There are $count X characters in the string";

这个问题:What do \S, \W, \D stand for in regex? 仅定义了各种 Perl 通配符运算符——其中一个(\S 运算符)我试图在我原来的问题中使用但无济于事。然而,它并没有演示如何实际使用这些运算符之一来获取字符串中所有非空白字符的计数。

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    来自perlfaq4 (How can I count the number of occurrences of a substring within a string?)

    另一个版本在列表上下文中使用全局匹配,然后分配 结果为一个标量,产生匹配数的计数。

    您还可以从命令行查询 Perl 文档:

    perldoc -q count

    use warnings;
    use strict;
    
    my $str = 'A b C $'; 
    my $cnt = () = $str =~ /\S/g;
    print "Char Count: $cnt\n";
    

    【讨论】:

      【解决方案2】:
      require 5.014;
      use feature qw( unicode_strings );
      
      my $count = () = $str =~ /\S/g;
      

      require 5.014;
      use feature qw( unicode_strings );
      
      my $count = 0;
      ++$count while $str =~ /\S/g;
      

      # Count non-whitespace characters.
      my $count = $str =~ tr/\x{0009}\x{000A}\x{000B}\x{000C}\x{000D}\x{0020}\x{0085}\x{00A0}\x{1680}\x{2000}\x{2001}\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}//c;
      
      • 第一个会占用大量内存。它为每个非空白字符创建一个标量。

      • 第二个没有。我不确定它是更快还是更慢。

      • 第三个应该快得多,但你不能使用预建的字符类。

      • \S 需要require 5.014; use feature qw( unicode_strings );(或只是use 5.014;)才能正确处理 U+85 NEL 和 U+A0 NBSP。 (更高版本也可以。)否则,它将“随机”被视为空格或非空格。

        use feature qw( say );
        
        { local $_ = "abc\x{0085}\x{00A0}\x{2000}"; say scalar( () = /\S/g ); }  # 3
        { local $_ = "abc\x{0085}";                 say scalar( () = /\S/g ); }  # 4?!
        { local $_ = "abc\x{00A0}";                 say scalar( () = /\S/g ); }  # 4?!
        { local $_ = "abc\x{2000}";                 say scalar( () = /\S/g ); }  # 3
        

      【讨论】:

        猜你喜欢
        • 2021-09-28
        • 2017-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-22
        • 2017-12-05
        • 2017-07-09
        • 1970-01-01
        相关资源
        最近更新 更多