Reputation: 5039
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
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
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