Programming Tips - regex: How to protect a string that is going to be used in a regular expression?

Date: 2012oct2 Update: 2026aug18 Language: perl, php, Java Q. regex: How to protect a string that is going to be used in a regular expression? A. In perl:
$ok_for_pattern = quotemeta($s);
# Now you can use it in a pattern without fear of it having meta characters, eg: $pat = '^' . $ok_for_pattern . '$';
In PHP:
$ok_for_pattern = quotemeta($s);
In Java:
String ok_for_pattern = Pattern.quote(s);