我正在遇到一个与网络脚本有关的Perl正则表达式匹配问题,我已经将这种行为放入了一个小片段中。
请看以下适用于Debian中Perl 5.10.0的Perl代码片段:
显然,第一种和第二种之间唯一的区别是将空格从提取的模式中移出,理论上不应该修改正则表达式,只是返回的部分不同。
我不明白为什么第二种和第三种不能像第一种一样工作。
编辑: 如果在$version is not the same script中删除括号,则不会得到匹配的结果,而是得到操作的布尔结果,要获得匹配的结果,需要在一个一元组中接收它(只有一个字符串进行匹配)。
请看以下适用于Debian中Perl 5.10.0的Perl代码片段:
#!/usr/bin/perl
use warnings;
use strict;
my $line = "Version: 0\r\n";
my($version) = $line =~ m/^Version:(\s\d+)\r\n$/;
print "1st failed \n" if not $version;
($version) = $line =~ m/^Version:\s(\d+)\r\n$/;
print "2nd failed \n" if not $version;
($version) = $line =~ m/^Version:\ (\d+)\r\n$/;
print "3th failed \n" if not $version;
使用以下输出:
2nd failed
3th failed
显然,第一种和第二种之间唯一的区别是将空格从提取的模式中移出,理论上不应该修改正则表达式,只是返回的部分不同。
我不明白为什么第二种和第三种不能像第一种一样工作。
编辑: 如果在$version is not the same script中删除括号,则不会得到匹配的结果,而是得到操作的布尔结果,要获得匹配的结果,需要在一个一元组中接收它(只有一个字符串进行匹配)。
0
。不同之处在于,第一个匹配项捕获了[ ]0
,而空格的存在使得 该 字符串被评估为 true。这就是为什么我至少没有立即看到它的原因。 - Telemachusprint "failed\n" unless ($version) = $line =~ ...
" 也许会起作用。 - Brad Gilbert