Masoud Abasian Masoud Abasian - 1 month ago 8
Perl Question

Exact matching with Question mark in Perl

I want to find string

?Allen
in the string array but there is question mark in keyword and it causes some problems.
I write this code to find string in array

@arr = ("My name is ?Allen",
"My name is ?Allens",
"My name is s?Allen",
"My name is s?Allens",
"My name is ?allen");
$keyword = "?Allen";
for (my $i=0; $i <= 4; $i++){
if ($arr[$i] =~ /\b$keyword\b/){
print "str $i = match\n";
}else{
print "str $i = no\n";
}
}


finally I get this result

str 0 = match
str 1 = no
str 2 = match
str 3 = no
str 4 = no


but I want to find only first index array as matching string like this:

str 0 = match
str 1 = no
str 2 = no
str 3 = no
str 4 = no

Answer

Note that your regex contains non-word special chars that you need to quote before using them in the actual pattern. Also, the fact that the special chars can appear at the leading/trailing positions means you cannot expect \b to always work the same (since its meaning is context dependent). Thus, you may fix the code with

/(?<!\S)\Q$keyword\E(?!\S)/

where

  • (?<!\S) - requires a whitespace char or start of string before
  • \Q$keyword\E - a literal search string (see Quoting Metacharacters)
  • (?!\S) - that should be followed with a whitespace or end of string.

Another alternative for \Q...\E (mentioned by Dave Cross) is using quotemeta:

This is the internal function implementing the \Q escape in double-quoted strings.