【问题标题】:Perl alternation match behaves differently with parenthesesPerl 交替匹配的行为与括号不同
【发布时间】:2014-07-10 22:51:56
【问题描述】:

有人可以解释为什么我的比赛表现不同,无论交替是否包含在捕获组中?

这可能是由于旧版本的 Perl(遗憾的是我无法控制),还是我误解了什么?我的理解是括号是某些人的惯例,但在这种情况下是不必要的。

[~]$ perl -v

This is perl, v5.6.1 built for PA-RISC1.1-thread-multi
(with 1 registered patch, see perl -V for more detail)

Copyright 1987-2001, Larry Wall

Binary build 633 provided by ActiveState Corp. http://www.ActiveState.com
Built 12:17:09 Jun 24 2002


Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using `man perl' or `perldoc perl'.  If you have access to the
Internet, point your browser at http://www.perl.com/, the Perl Home Page.

[~]$ perl -e 'print "match\n" if ("getnew" =~ /^get|put|remove$/);'
match
[~]$ perl -e 'print "match\n" if ("getnew" =~ /^(get|put|remove)$/);'
[~]$

【问题讨论】:

    标签: regex perl alternation


    【解决方案1】:

    ^get|put|remove$ 查找 ^getputremove$。因此,“getnew”与该模式匹配,因为它以 get 开头。

    ^(get|put|remove)$ 查找^get$^put$^remove$

    【讨论】:

    • 每天学习新东西。有道理,但我没有意识到交替会延伸到那些。谢谢!
    • 如果您实际上不需要捕获,请使用非捕获括号:/^(?:get|put|remove)$/
    • @ysth:也很高兴知道,谢谢。在这种情况下,捕获不会受到伤害,所以我会为自己节省额外的几个字符。
    【解决方案2】:

    根据设计,如果将“或”| 括在括号中,则它与捕获组隔离。

    第二个正则表达式在 3 个单词周围使用括号,因此通过传递性属性等价于以下内容:

    if ("getnew" =~ /^get$/ || "getnew" =~ /^put$/ || "getnew" =~ /^remove$/) {
         print "match\n" ;
    }
    

    但是,第一个正则表达式没有括号,因此“或”会影响整个表达式,包括边界条件。它匹配是因为第一个测试 /^get/ 成功:

    if ("getnew" =~ /^get/ || "getnew" =~ /put/ || "getnew" =~ /remove$/) {
         print "match\n" ;
    }
    

    【讨论】:

    • 感谢您的回答。你和 taggon 的回答都非常接近,但我只能接受一个答案……而 taggon 才刚刚开始。 :)
    • @Sbrocket Heh,他比我长了大约 5 个月,但不用担心 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2021-10-12
    相关资源
    最近更新 更多