how do you match two strings in two different variables using regular expressions?
$a='program';
$b='programming';
if ($b=~ /[$a]/){print "true";}
this is not working
开发者_如何学Pythonthanks every one i was a little confused
The []
in regex mean character class which match any one of the character listed inside it.
Your regex is equivalent to:
$b=~ /[program]/
which returns true as character p
is found in $b
.
To see if the match happens or not you are printing true
, printing true
will not show anything. Try printing something else.
But if you wanted to see if one string is present inside another you have to drop the [..]
as:
if ($b=~ /$a/) { print true';}
If variable $a
contained any regex metacharacter then the above matching will fail to fix that place the regex between \Q
and \E
so that any metacharacters in the regex will be escaped:
if ($b=~ /\Q$a\E/) { print true';}
Assuming either variable may come from external input, please quote the variables inside the regex:
if ($b=~ /\Q$a\E/){print true;}
You then won't get burned when the pattern you'll be looking for will contain "reserved characters" like any of -[]{}()
.
(apart the missing semicolons:) Why do you put $a
in square brackets? This makes it a list of possible characters. Try:
$b =~ /\Q${a}\E/
Update
To answer your remarks regarding =
and =~
:
=~
is the matching operator, and specifies the variable to which you are applying the regex ($b
) in your example above. If you omit=~
, then Perl will automatically use an implied$_ =~
.- The result of a regular expression is an array containing the matches. You usually assign this so an array, such as in
($match1, $match2) = $b =~ /.../;
. If, on the other hand, you assign the result to a scalar, then the scalar will be assigned the number of elements in that array.
So if you write $b = /\Q$a\E/
, you'll end up with $b = $_ =~ /\Q$a\E/
.
$a='program';
$b='programming';
if ( $b =~ /\Q$a\E/) {
print "match found\n";
}
If you're just looking for whether one string is contained within another and don't need to use any character classes, quantifiers, etc., then there's really no need to fire up the regex engine to do an exact literal match. Consider using index
instead:#!/usr/bin/env perl
#!/usr/bin/env perl
use strict;
use warnings;
my $target = 'program';
my $string = 'programming';
if (index($string, $target) > -1) {
print "target is in string\n";
}
精彩评论