简体   繁体   English

如何在Perl中的匹配正则表达式中包含变量,并检查变量是否在字符串中?

[英]How can I include a variable in a match regular expression in Perl, and check if the variable is NOT in the string?

I would like to include a variable in a match regular rexpression, in Perl, and check if the variable is NOT in the string. 我想在Perl中的匹配常规rexpression中包含一个变量,并检查该变量是否在字符串中。

The link here instructs how to include the variable, but I'm having difficulty testing if the variable is NOT matched. 这里的链接指示如何包含变量,但是如果变量不匹配,我将难以测试。 Sure, I could just negate an if conditional like this: 当然,我可以像这样否定if条件:

if (!($string =~ m/$Myvar/)) {
# Do some code here
}

But I'm sure there must be a way to do within the regular expression match. 但我确信在正则表达式匹配中必须有办法。 Any ideas? 有任何想法吗?

Thank you for your help, in advance. 提前谢谢你的帮助。

Use the !~ operator. 使用!~运算符。

if ($string !~ m/$Myvar/) {
# Do some code here
}

Or use index and avoid the regular expression engine altogether. 或者使用index并完全避免使用正则表达式引擎。 This will work even if $Myvar has characters that the regular expression engine treats specially. 即使$Myvar具有正则表达式引擎专门处理的字符,这也会起作用。

if ( index($string, $Myvar) < 0 ) {
# Do some code here
}

What's wrong with negating the result? 否定结果有什么问题?

A "negative match" (requiring a negative lookahead assertion ) makes your regex much more complicated: “负面匹配”(需要一个负面的先行断言 )会使你的正则表达式更加复杂:

if ($string =~ m/^(?!.*$Myvar)/s) {
    # Do some code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM