2010-09-12 122 views

回答

7

您可以使用dirname功能從File::Basename

dirname($path) eq '/this/is/my/dir/name' or warn "No match"; 

UPD:如果你喜歡使用正則表達式:

my $dirname = '/this/is/my/dir/name'; 
$path =~ m|^$dirname/[^/]+/?$| or warn "No match"; 
+0

+1謝謝,這個工程,但我想要一個正則表達式(我用這一堆其他測試)。 – 2010-09-12 11:54:32

+3

@David:正則表達式不是這裏最好的選擇 - File :: Basename是爲了處理文件名解析中的混亂邊緣情況而編寫的。應該沒有理由不能將其與其他測試結合使用。 – Ether 2010-09-12 16:44:18

3

斜槓存在問題的默認分隔符,你風與leaning toothpick problem。幸運的是,Perl 5允許您選擇自己的分隔符,如果您使用一般形式:m//。既然你想整個字符串,而不只是一個子串的匹配,你將要使用指定start of string (^) and end of string ($)主播:

if ($dirname =~ m{^/this/is/my/dir/name/anything$}) { 
} 

注:^$錨由/m modifier(他們改變意味着開始影響和行結束)。如果您打算使用/m修飾符,則可能需要使用\A (start of string) and \Z (end of string or before a newline at the end of the string) or \z (end of string) assertions

+0

+1謝謝,這很有用!我明白'm'後的表達式可以用'{}'或'||'或'//'括起來嗎? – 2010-09-12 13:46:59

+0

@大衛B:是的。不記得官方說明,但[這個也解釋](http://perldoc.perl.org/perlop.html#Gory-details-of-parsing-quoted-constructs)。 – Dummy00001 2010-09-12 13:59:58

+1

@David B在Perl 5中,您可以選擇任何分隔符,但可以使用空格字符。有四個包圍分隔符集:'[]','{}','()'和'<>'。在所有其他情況下,您可以使用這種'm#regex#'或#s#regex#string#'這樣的字符。分隔符'''也是特殊的。它將構造變成它自己的非插值版本。 – 2010-09-12 14:22:46

相關問題