jherran jherran - 6 months ago 8
Perl Question

Regex does not work with input string containing + inside

I have the following piece of code:

$url = "http://www.example.com/url.html";
$content=Encode::encode_utf8(get $url);

$nameaux = Encode::encode_utf8($DBfield);

if($content =~ />$nameaux<\/a><\/td><td class="class1">(.*?)<\/td>/ ||
$content =~ />$nameaux<\/a><\/td><td class="class2">(.*?)<\/td>/ ||
$content =~ />$nameaux<\/a><\/td><td class="class3">(.*?)<\/td>/ ) {
... more code ...
}


This piece of code works great except when
$DBfield
is equal to a string containing a plus (ex. A+1) on it that exists on
$content
.

Could someone explain my how to handle this?

Answer

If $nameaux can contain regex characters (like +), you need to escape the field to a regex literal by wrapping with \Q ... \E.

$content =~ />\Q$nameaux\E<\/a><\/td><td class="class1">(.*?)<\/td>/ ||

So + will be just a plus sign and not mean "one or more of", which is why your regex doesn't match.

Comments