检测列表上下文中的匹配与捕获与非捕获正则表达式的区别?

根据 perlretut

… in scalar context,$time =~ /(\d\d):(\d\d):(\d\d)/ returns a true or false value. In list context,however,it returns the list of matched values ($1,$2,$3) .

但是,如果在regexp中没有捕获组时模式匹配,我找不到列表上下文中返回内容的解释.测试表明它是list(1)(单个元素,整数1). (辅助问题 – 它总是这样,它在哪里定义?)

这使我很难做到我想要的:

if (my @captures = ($input =~ $regexp)) {
    furtherProcessing(@captures);
}

我希望在匹配时调用FurtherProcessing,并将任何捕获的组作为参数传递.当$regexp不包含任何捕获组时问题就出现了,因为我希望在没有参数的情况下调用FurtherProcessing,而不是使用上面发生的值1.我无法测试(1)作为特殊情况,就像这样

if (my @captures = ($input =~ $regexp)) {
    shift @captures if $captures[0] == 1;
    furtherProcessing(@captures);
}

因为在这种情况下

$input = 'a value:1';
$regexp = qr/value:(\S+)/;

@captures中有一个捕获的值,看起来与$regexp匹配但没有捕获组时得到的值相同.

有办法做我想要的吗?

您可以使用 $#+查找上次成功匹配中有多少组.如果那是0,则没有组,你有(1). (是的,如果没有组,将始终是(1),如 perlop中所述.)

所以,这将做你想要的:

if (my @captures = ($input =~ $regexp)) {
    @captures = () unless $#+; # Only want actual capture groups
    furtherProcessing(@captures);
}

请注意,$#计算所有组,无论它们是否匹配(只要整个RE匹配).那么,“hello”=〜/ hello(world)?/将返回1组,即使该组不匹配(@captures中的值将是undef).

相关文章

jquery.validate使用攻略(表单校验) 目录 jquery.validate...
/\s+/g和/\s/g的区别 正则表达式/\s+/g...
自整理几个jquery.Validate验证正则: 1. 只能输入数字和字母...
this.optional(element)的用法 this.optional(element)是jqu...
jQuery.validate 表单动态验证 实际上jQuery.validate提供了...
自定义验证之这能输入数字(包括小数 负数 ) <script ...