user717236
user717236

Reputation: 5039

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.

Upvotes: 2

Views: 229

Answers (2)

robert
robert

Reputation: 34438

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
}

Upvotes: 8

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

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
}

Upvotes: 2

Related Questions