如何使用 Perl 获取期望值



在数组@fruit中,有很多值。我想搜索该行是否包含数组中的值。

我想找出"新鲜苹果"而不是"苹果"。 但我的代码将同时返回"新鲜苹果"和"苹果":

my $line = "this is one fresh apple!";
my @fruit= ("apple","fresh apple","banana","fresh banana","rice");
foreach my $fruit(@fruit){
if ($line =~ /$fruit/){
print "$fruit n";
}
}

最简单的方法可能是 a( 对数组进行排序,以便最长的字符串首先出现,b( 找到匹配项后停止搜索:

my $line = "this is one fresh apple!";
my @fruit= ("apple","fresh apple","banana","fresh banana","rice");
@fruit = sort { length $b <=> length $a } @fruit;
foreach my $fruit(@fruit){
if ($line =~ /$fruit/){
print "$fruit n";
last;
}
}

您可以通过创建单个正则表达式并避免循环来改善这一点:

use feature 'say';
my $line = "this is one fresh apple!";
my @fruit= ("apple","fresh apple","banana","fresh banana","rice");
@fruit = sort { length $b <=> length $a } @fruit;
my $re = 'b(' . join('|', @fruit) . ')b';
if ($line =~ /$re/) {
say $1;
}

只是你需要在一行上打勾。

my $line = "this is one fresh apple!";
my @fruit= ("apple","fresh apple","banana","fresh banana","rice");
foreach my $fruit(@fruit)
{

Validate the array here检查值applespace

next if($fruit=~m/^apple$/ || $fruit!~m/[ ]/); 

Skip the value of apple

if ($line =~ / $fruit/){
print "$fruit n";
}
}

如果你想要"longuest"匹配,一个选项是在你遍历数组时跟踪它:

use strict;
use warnings;
my $line =  "this is one fresh apple!";
my @fruit = ("apple","fresh apple","banana","fresh banana","rice");
my $res;
my $res_length = -1;
for my $fruit(@fruit) {
next if $line !~ /$fruit/;
next if length($fruit) <= $res_length;
$res = $fruit;
$res_length = length($fruit);
}
print $res, "n" if $res_length > 0;

最新更新