regex - 计算 Perl 中字符串中非空白字符的数量

标签 regex perl

<分区>

我想弄清楚如何计算字符串中的任何和所有非空白字符,以便在下面的示例中我会得到 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 运算符)我试图在我的原始问题中使用但无济于事。然而,它并未演示如何实际使用这些运算符之一来获取字符串中所有非空白字符的计数。

最佳答案

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

Another version uses a global match in list context, then assigns the result to a scalar, producing a count of the number of matches.

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

perldoc -q count

use warnings;
use strict;

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

关于regex - 计算 Perl 中字符串中非空白字符的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66375965/

相关文章:

java - Java 中用于密码模式的正则表达式

perl - 我可以在shebang行中将perl的开关与/bin/env一起使用吗?

perl - 如何在 Perl 中将十进制数转换为二进制数?

Perl 取消引用特定值的数组

java - 正则表达式的多重匹配?

javascript - 在正则表达式中使用 '|' 运算符时确定匹配的子模式

c# - 正则表达式查找 html 标签后缺失的空格

perl - 读取带有嵌入换行符的 CSV 文件

Perl 在 void 上下文中对私有(private)变量的无用使用

java - 将字符串拆分为字符串数组 Java