我正在使用perl正则表达式匹配我所拥有的网络脚本的问题,我已经设法将行为放在一个小片段中.
在Debian中将这个Perl片段用于Perl 5.10.0:
#!/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;
Run Code Online (Sandbox Code Playgroud)
有了这个输出:
2nd failed
3th failed
Run Code Online (Sandbox Code Playgroud)
显然,第一和第二之间的唯一区别是将空间移出提取的模式,理论上不应该修改正则表达式,只返回返回的部分.
我不明白为什么第二和第三不完全像第一个一样.
编辑:如果你删除$ version中的括号不是相同的脚本,你得不到匹配的结果,你得到op的布尔结果,以获得你需要在一元中接收它的匹配结果(只有一个)字符串匹配)元组.
cha*_*aos 12
问题是你正在测试布尔值true,因为在后两种情况下你提取的字符串值为false(字符串'0').试试这个:
$line = "Version: 0\r\n";
my $version;
($version) = $line =~ m/^Version:(\s\d+)\r\n$/;
print "1st failed \n" unless defined $version;
($version) = $line =~ m/^Version:\s(\d+)\r\n$/;
print "2nd failed \n" unless defined $version;
($version) = $line =~ m/^Version:\ (\d+)\r\n$/;
print "3th failed \n" unless defined $version;
Run Code Online (Sandbox Code Playgroud)