直到几分钟前,我还相信Perl的 $
匹配任何类型的行尾。不幸的是,我的假设被证明是错误的。
以下脚本仅删除 $string3
的单词 end。
use warnings;
use strict;
my $string1 = " match to the end" . chr(13);
my $string2 = " match to the end" . chr(13) . chr(10);
my $string3 = " match to the end" . chr(10);
$string1 =~ s/ end$//;
$string2 =~ s/ end$//;
$string3 =~ s/ end$//;
print "$string1\n";
print "$string2\n";
print "$string3\n";
但我几乎 75% 确信我见过 $
至少匹配 chr(13).chr(10)
的情况。
那么,$
原子到底匹配什么(以及在什么情况下)?
最佳答案
首先,取决于/m
修饰符是否有效。
当 /m
处于事件状态时,它在 \n
字符之前或字符串末尾匹配。它相当于 (?=\n|\z)
。
如果没有 /m
,则在 \n
字符之前(如果该字符是字符串的最后一个字符)或字符串末尾的字符进行匹配。它相当于 (?=\n?\z)
。
它与通用换行符不匹配。 \R
元字符(在 5.10.0 中引入)可以执行此操作(但没有 $
的字符串结尾属性)。您可以在之前的等效项之一中将 \R
替换为 \n
,以获得与通用换行符匹配的 $
类似功能。
请注意,\n
并不总是 chr(10)
。这取决于平台。目前使用的大多数平台的 \n
表示 chr(10)
,但情况并非总是如此。例如,在较旧的 Mac 上,\n
为 chr(13)
,\r
为 chr(10)
.
关于regex - Perl 中 $ 到底匹配什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10445960/