I am doing the pattern matching as below. But I am not getting the proper output. Please suggest the correct code to get the correct output.
#! /usr/bin/perl -w
my $subString = "1.3.6.1.2.1.26.2.1.1.1.";
my $wholeString = "1.3.6.1.2.1.26.2.1.1.12.1";
if ($wholeString =~ m/^$subString/)
{
print "matched string is : $&\n";
print "Wrong!!!!\n";
}
else
{
print "matched string is : $&\n";
print "Right!!!!!\n";
}
Actual Output: matched string is : 1.3.6.1.2.1.26.2.1.1.12 Wrong!!!!
Expected Output: matched string is : 1.3.6.1.2.1.26.2.1.1.1. Right!!!!!
What should I change in the code to get the expected output? Please
The dot has a special meaning in a regex - it means "match any character here". So the ".1." at the end of your substring is quite happy to match the ".12" in your test string.
To remove the special meaning of dot (and all other special characters) you can use the \Q
escape sequence.
if ($wholeString =~ m/^\Q$subString/)
But (as has already been pointed out in the comments), a regex match is probably not the right tool here. You probably need the index()
function.
if (index($wholeString, $subString) == 0)
.
matches any character in a regex and it looks like you want to check if $wholeString
starts with $subString
without regex matching. This can be done using substr
:
if(substr($wholeString, 0, length($subString)) eq $subString) {
# $wholeString starts with $subString
} else {
# $wholeString does not start with $subString
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With