Perl REGEX应该不匹配

时间:2014-08-11 10:13:11

标签: regex perl

所以我有2个变量,一个是短字符串,另一个是长字符串,应该包含短字符串。我已经在脚本中添加了一些打印件但是匹配不起作用 - 任何人都可以为我解释这一点:

print OUT "Omni: [$omnihostname]\n";
print OUT "API: $api\n";
print OUT "Match: Y\n" if ($omnihostname =~ /$api/i);
print OUT "Match: N\n" if ($omnihostname !~ /$api/i);
print OUT "-----------------------------------------------------------\n";

这是输出:

Omni: [ASW02SLO]
API: deviceDetail@deviceId = 10401381@hostName = ASW02SLO@ipAddress = [other redundant text here]
Match: N
-----------------------------------------------------------

谢谢, 本

2 个答案:

答案 0 :(得分:4)

在我看来,你的术语在正则表达式中是错误的,即你想确定$omnihostname中是否包含较短的字符串$API,而不是相反。< / p>

因此,有一个比正则表达式更好的解决方案:

if (index($API, $omnihostname) >= 0);  # Match: Y

如果需要不区分大小写,请根据需要在lc(...)中包装其中一个或两个参数。

注意:fc(...)是更高版本Perl中案例折叠的首选。

答案 1 :(得分:0)

这就是我这样做的方式:

use strict;
use warnings; 

my $ss = 'string'; # your 'key'

my @ls = qw(longstring longstringlong longstri); # an array to search through

foreach(@ls){
    chomp;
    print "Match! $_\n" if /$ss/; 
    print "No match! $_\n" if ! /$ss/;
}

Match! longstring
Match! longstringlong
No match! longstri