首页 > 解决方案 > 为什么这不计算字符串末尾的 CRLF?

问题描述

我有这段代码,我希望它可以计算字符串末尾的 CRLF。它目前不起作用,我不明白为什么。

printf "text is [%s]", $text;   # debug this
my $number = ( $text =~ /\R$/ );
sprintf "File has [%i] errant CRLFs at the EOF\n", $number;

标签: regexperl

解决方案


有几个问题。您需要使用全局匹配来查找多个匹配项。您的正则表达式也与最后一个匹配\R

因此,对于正则表达式,请使用 this m/\R(?=\R*$)/g\R它必须后跟 0 或更多\R,然后是字符串的结尾。

另一个问题是这my $number = ( $text =~ /\R$/ );不会返回匹配的数量。1如果有匹配则返回。您应该为此使用while循环(带有g正则表达式的标志)

最后,最后一行应该printf代替sprintf

use strict;
use warnings;

my $text = "ASD
ASD
ASD
ASD





";

printf "text is [%s]", $text;   # debug this

my $number = 0;
$number++ while $text =~ m/\R(?=\R*$)/g;
# # or use this instead:
# my $number = () = $text =~ m/\R(?=\R*$)/g;


printf "\n\nFile has [%i] errant CRLFs at the EOF\n", $number;

输出:

text is [ASD
ASD
ASD
ASD





]

File has [6] errant CRLFs at the EOF

推荐阅读