Perlre in Perldoc没有详细介绍负面看法,但我尝试过测试,并没有按预期工作。我想看看我是否可以区分C预处理器宏定义(例如#define MAX(X)....)与实际使用情况(y = MAX(x);),但它没有按预期工作。
my $macroName = 'MAX';
my $macroCall = "y = MAX(X);";
my $macroDef = "# define MAX(X)";
my $boundary = qr{\b$macroName\b};
my $bstr = " MAX(X)";
if ( $bstr =~ /$boundary/ ) {
print "boundary: $bstr matches: $boundary\n";
} else {
print "Error: no match: boundary: $bstr, $boundary\n";
}
my $negLookBehind = qr{(?<!define)\b$macroName\b};
if ( $macroCall =~ /$negLookBehind/ ) { # "y = MAX(X)" matches "(?<!define)\bMAX\b"
print "negative look behind: $macroCall matches: $negLookBehind\n";
} else {
print "no match: negative look behind: $macroCall, $negLookBehind\n";
}
if ( $macroDef =~ /$negLookBehind/ ) { # "#define MAX(X)" should not match "(?<!define)\bMAX\b"
print "Error: negative look behind: $macroDef matches: $negLookBehind\n";
} else {
print "no match: negative look behind: $macroDef, $negLookBehind\n";
}
似乎$macroDef
和$macroCall
似乎都匹配正则表达式/(?<!define)\b$macroName\b/
。我退出原来的/(?<\#)\s*(?<!define)\b$macroName\b/
,因为那也没有用。那我搞砸了什么? Perl是否允许链接多个环绕表达式?
答案 0 :(得分:2)
define
(?<!define)
之后你遗漏了一个空格。修正:
my $negLookBehind = qr{(?<!define )\b$macroName\b};
请注意:正反面断言需要固定宽度。如果不是这种情况,那么它们的使用将导致匹配时间呈指数增长。 (唯一的例外是特殊的\K
转义码)
有关其他参考:perlretut - Looking ahead and looking behind
至于你的另一个问题:“ Perl是否允许链接多个环绕表达式?”。答案是肯定的。