以下内容:
~$ perl -e '
my $var = "March 1998";
$var =~ /([0-9]*)/;
print "$1\n";
什么都没打印出来。我无法理解为什么,但在考虑了一下之后,我认为它与数字部分不匹配,因为它需要0或更多次出现的数字并且整行满足。但是,我怎样才能真正看到/“捕捉”它实际匹配的内容以验证我的假设>
答案 0 :(得分:4)
$1
包含捕获的内容,因此您正确地执行此操作。
特殊变量$'
,$&
和$`
也会有所帮助。有关详细信息,请参阅perlvar
。
$match = $var =~ /([0-9]*)/;
print "There ", ($match ? "was" : "was not"), " a match\n";
print "The captured expression was '$1'\n";
print "The matched expression was '$&'\n"; # includes chars outside capture groups
print "Expression before the match was '$`'\n";
print "Expression after the match was '$''\n";
从Perl 5.10开始,您还可以使用/p
修饰符和更具可读性的${^PREMATCH}
,${^MATCH}
,${^POSTMATCH}
变量。
$match = $var =~ /([0-9]*)/p;
print "There ", ($match ? "was" : "was not"), " a match\n";
print "The captured expression was '$1'\n";
print "The matched expression was '${^MATCH}'\n";
print "Expression before the match was '${^PREMATCH}'\n";
print "Expression after the match was '${^POSTMATCH}'\n";
答案 1 :(得分:4)
如前所述,永远不要检查$1
,$2
等,而不检查匹配是否成功。否则,这些变量将包含最近成功的正则表达式匹配后包含的内容。一个例外是当正则表达式可以匹配任何字符串 - 就像你的那样,虽然你可能没有意识到 - 但这种情况很少见,并且最好养成总是测试比赛成功的习惯
@-
和@+
变量分别给出了作为上一次成功的正则表达式匹配对象的字符串中匹配捕获组的开始和结束索引。
if ($var =~ /([0-9]*)/) {
print "The first capturing group matched from index $-[1] to index $+[1].\n";
}
这打印The first capturing group matched from index 0 to index 0.
果然,你的字符串以零数字开头,这就是匹配的内容。