Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex does not work with input string containing + inside

Tags:

regex

perl

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?

like image 674
jherran Avatar asked Jun 16 '26 11:06

jherran


1 Answers

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.

like image 200
Bohemian Avatar answered Jun 19 '26 05:06

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!