Is there a built-in way to escape a string that will be used within/as a regular expression? E.g.
www.abc.com
The escaped version would be:
www\.abc\.com
I was going to use:
$string =~ s/[.*+?|()\[\]{}\\]/\\$&/g; # Escapes special regex chars
But I just wanted to make sure that there’s not a cleaner built-in operation that I’m missing?
Use
quotemetaor\Q...\E.Consider the following test program that matches against
$stras-is, withquotemeta, and with\Q...\E:Notice in the output that using the string as-is could produce spurious matches:
For programs that accept untrustworthy inputs, be extremely careful about using such potentially nasty bits as regular expressions: doing so could create unexpected runtime errors, denial-of-service vulnerabilities, and security holes.