我知道
if ( grep(/^$pattern$/, @array) ) {...}
如果在陣列的元素中找到整個字串,它將回傳 true。但是,我試圖弄清楚如果陣列中的一個元素與字串末尾的部分匹配,如何回傳 true。
例如:
my @array = (".com", ".net", ".org");
my $domain = "www.example.com"; #<--Returns True
$domain = "www.example.gov"; #<--Returns False
$domain = "www.computer.gov"; #<--Returns False, .com not at end
有沒有更優雅的方法來做到這一點,而無需創建foreach()和使用m//對每個元素的匹配?
uj5u.com熱心網友回復:
可以any從List::Util使用
if ( any { $re = quotemeta; $string =~ /$re$/ } @ary ) { ... }
匹配字串的$結尾,因此上面的匹配任何模式在$string其$re結尾(不管該字串中的前面是什么)。quotemeta轉義所有“ ASCII 非單詞字符”,因此(也)在正則運算式中具有特殊含義的事物。在這種情況下,它將.(匹配任何字符的模式)轉換\.為文字點。
quotemeta有一種\Q ... \E可以在正則運算式中使用的形式,例如
if ( any { $string =~ /\Q$_\E$/ } @ary ) { ... }
但要小心不要逃避可能更復雜模式的其他部分。
uj5u.com熱心網友回復:
怎么樣
my @array = (".com", ".net", ".org");
my $pattern = join "|", map quotemeta, @array;
if ($domain =~ /(?:$pattern)$/) # $ matches end of string
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425547.html
上一篇:Perl使用bash反引號
