简体   繁体   中英

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.

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 (!($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. This will work even if $Myvar has characters that the regular expression engine treats specially.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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