加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 22:53:45 所属栏目:百科 来源:网络整理
导读:根据 perlretut … in scalar context, $time =~ /(dd):(dd):(dd)/ returns a true or false value. In list context,however,it returns the list of matched values ($1,$2,$3) . 但是,如果在regexp中没有捕获组时模式匹配,我找不到列表上下文中返回
根据 perlretut

… in scalar context,$time =~ /(dd):(dd):(dd)/ 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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读