Reputation: 47
How do match the two strings which contains brackets.
the perl code is here.
#!/usr/bin/perl -w
$a = "cat(S1)rat";
$b = "cat(S1)r";
if ( $a =~ $b ) {
printf("matching\n");
}
I am not getting the desired output.
please help
snk
Upvotes: 0
Views: 1652
Reputation: 11124
There are several answers here, but not a lot address your fundamental misunderstanding.
Here is a simplified version of your problem:
my $str = "tex(t)";
my $pattern = "tex(t)";
if ($str =~ $pattern) {
print "match\n";
} else {
print "NO MATCH\n";
}
This prints out NO MATCH
.
The reason for this is the behavior of the =~
operator.
The thing on the left of that operator is treated as a string, and the thing on the right is treated as a pattern (a regular expression).
Parentheses have special meaning in patterns, but not in strings.
For the specific example above, you could fix it with:
my $str = "tex(t)";
my $pattern = "tex\\(t\\)";
More generally, if you want to escape "special characters" in $pattern
(such as *
, .
, etc.), you can use the \Q...\E
syntax others have mentioned.
Does it make sense?
Typically, you do not see a pattern represented as a string (as with "tex(t)"
).
The more common way to write this would be:
if ($str =~ /tex(t)/)
Which could be fixed by writing:
if ($str =~ /tex\(t\)/)
Note that in this case, since you are using a regex object (the /.../
syntax), you do not need to double-escape the backslashes, as we did for the quoted string.
Upvotes: 3
Reputation: 91478
You have to escape the parenthesis:
if ( $a =~ /\Q$b/ ) {
print "matching\n";
}
And please, avoid using variable names $a
and $b
they are reserved for sorting.
Also, there're no needs to use printf
here.
Upvotes: 1
Reputation: 902
Try this code:
my $p = "cat(S1)rat";
my $q = "cat(S1)r";
if ( index( $p, $q ) == -1 ) {
print "Does not match";
} else {
print "Match";
}
Upvotes: 1