2014-07-10 41 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