所以我没有什么问题,我需要检查perl,如果字符串中的最后一个字符是" a"。我知道,我可以这样做:
$test = "mama";
$test2 = substr $test, -1
现在只检查$ test2是否不等于" a"。但是我怎么能用正则表达式做到这一点?
答案 0 :(得分:5)
$
匹配字符串的结尾:
my $test = "mama";
print "Terminal 'a' in $test\n" if $test =~ /a$/;
答案 1 :(得分:0)
在Perl中,$
does not necessarily match the end of the string:
^ Match string start (or line, if /m is used) $ Match string end (or line, if /m is used) or before newline \b Match word boundary (between \w and \W) \B Match except at word boundary (between \w and \w or \W and \W) \A Match string start (regardless of /m) \Z Match string end (before optional newline) \z Match absolute string end \G Match where previous m//g left off \K Keep the stuff left of the \K, don't include it in $&
因此,要检查$s
的最后一个字符是否真的是'a'
,您必须使用:
if ($s =~ /a\z/) { ...
,因为
$ perl -E 'say "yes" if "a\n" =~ /a$/' yes