1

Can someone explain why my match behaves differently whether or not the alternation is enclosed within a capture group?

Is this possibly due to the old version of Perl (which I have no control over, sadly), or am I misunderstanding something? My understanding was that the parentheses were a convention for some people but otherwise unnecessary in this case.

[~]$ 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)$/);'
[~]$
4

2 回答 2

6

^get|put|remove$找到^getorputremove$。因此,“getnew”与模式匹配,因为它以get.

^(get|put|remove)$发现^get$or^put$^remove$.

于 2014-07-10T22:57:50.447 回答
2

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

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

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

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

if ("getnew" =~ /^get/ || "getnew" =~ /put/ || "getnew" =~ /remove$/) {
     print "match\n" ;
}
于 2014-07-10T22:57:15.347 回答