Possible Duplicate:
How can I escape meta-characters when I interpolate a variable in Perl's match operator?
I am using the following regex to search for a string $word in the bigger string $referenceLine as follows :
$wordRefMatchCount =()= $referenceLine =~ /(?=\b$word\b)/g
The problem happens when my $word substring contains some (, etc. Because it takes it as a part of the regex rather than the string to match and gives the following error :
Unmatched ( in regex; marked by <-- HERE in
m/( <-- HERE ?=\b( darsheel safary\b)/
at ./bleu.pl line 119, <REFERENCE> line 1.
Can somone please tell me a solution to this? I think If I could somehow get perl to understand that we want to look for the whole $word as it is without evaluating it, it might work out.
Use
to tell the regex engine to treat every character in
$wordas a literal character.\Qmarks the start,\Emarks the end of a literal string in Perl regex.Alternatively, you could do
and then use
One more thing (taken up here from the comments where it’s harder to find:
Your regex fails in your example case because of the word boundary anchor
\b. This anchor matches between a word character and a non-word character. It only makes sense if placed around actual words, i. e.\bbar\bto ensure that onlybaris matched, notfoobarorbarbaric. If you put it around non-words (as in\b( darsheel safary\b) then it will cause the match to fail (unless there is a letter, digit or underscore right before the().