regex - 为什么这不计算字符串末尾的 CRLF?
问题描述
我有这段代码,我希望它可以计算字符串末尾的 CRLF。它目前不起作用,我不明白为什么。
printf "text is [%s]", $text; # debug this
my $number = ( $text =~ /\R$/ );
sprintf "File has [%i] errant CRLFs at the EOF\n", $number;
解决方案
有几个问题。您需要使用全局匹配来查找多个匹配项。您的正则表达式也与最后一个匹配\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
推荐阅读
- javascript - 引导表样式不适用于 window.print();
- javascript - 非法退货声明
- protractor - 浏览器堆栈测试结果仪表板 Rest API 结果列显示未标记
- java - 如何在存储的 Mongo DB 图像上进行 Tesseract Ocr
- rspec - Rspec:如何期望表内的href链接
- asp.net-core - 路由:iis 不工作/独立工作 - asp.net core 3.0
- html - 是否可以在 HTML 中初始化表单而不必单独初始化所有输入字段?
- python - Pandas : filter the rows based on a column containing lists
- google-chrome - 如何删除 PWA 图标上的 Chrome Android 徽章
- ios - 必须从 Xcode 11.2 中的主线程使用获取警告,并且应用程序崩溃,在 Xcode 10.2 中未收到警告