你可以使用grep将字符串与“模板”字符串进行比较吗?

时间:2014-06-11 17:54:32

标签: regex perl

my @array = (
   'There were \d* errors that occurred',
   'Your system exploded because \.*',
);

my $error = 'There were 22 errors that occurred';
if (grep(/$error/, @array)) {
   print 'That error is ok, continue...';
} else {
   die;
}

在perl中是否有任何方法可以将完整字符串与包含正则表达式的字符串进行比较? 就像在这个例子中我想要两个$ error ='发生了22个错误'和$ error ='发生了12341235个错误'被比作一种"模板"如果匹配,则返回一个布尔值。我想,使用grep可能是不可能的。

也许这样的事情确实有效:

my @s = ('there were \d* errors');

print _error_checker(@s, 'there were 10 errors');

sub _error_checker {
    my (@acceptable_errors, $text) = @_;

    foreach my $error (@acceptable_errors) {
        if ($text =~ /$error/) {
            return 1;
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:6)

你很接近,你只需要在grep中反转你的测试。

my @ok_errors = (
   'There were \d* errors that occurred',
   'Your system exploded because \.*',
);

my $errmsg = 'There were 22 errors that occurred';
if (grep {$errmsg =~ /$_/} @ok_errors) {
   print 'That error is ok, continue...';
} else {
   die;
}

此外,您可以使用qr{}

缓存正则表达式
my @ok_errors = (
   qr{There were \d* errors that occurred},
   qr{Your system exploded because \.*},
);

my $errmsg = 'There were 22 errors that occurred';
if (grep {$errmsg =~ $_} @ok_errors) {
   print 'That error is ok, continue...';
} else {
   die;
}