2014-07-10 42 views
1

有人可以解释为什么我的匹配行为有所不同,不管交替是否包含在捕获组中?Perl交替匹配的行为与圆括号不同

这是否可能是由于旧版本的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)$/);' 
[~]$ 

回答

6

^get|put|remove$发现^getputremove$。所以,“getnew”匹配模式,因为它以get开头。

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

+0

每天学习新的东西。有意义,但我没有意识到,这种变化将延伸到那些。谢谢! –

+1

如果你实际上并不需要捕获,使用非捕获的parens:'/ ^(?: get | put | remove)$ /' – ysth

+0

@ysth:同样很高兴知道,谢谢。在这种情况下,捕捉不会伤害,所以我会为自己节省额外的情侣角色。 –

2

通过设计,一个“或” |是,如果它被包围在括号中分离到的捕获基团。

的第二正则表达式使用括​​号周围的3个字,所以它等效于由传递特性如下:

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

然而,第一正则表达式没有括号,因此,“或”效应的整个表达式包括边界条件。它匹配,因为第一次测试,/^get/,成功:

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

谢谢你的回答。你和塔格龙在回答时都非常接近,但我只能接受一个答案......而塔格刚刚刚开始。 :) –

+0

@Sbrocket嘿,他比我有5个月的时间了,但不用担心;) – Miller