I have a string which may hold special characters like: $
, (
, @
, #,
etc.
I need to be able to perform regular expressions on that string.
Right now if my string has any of these characters the regex seems to break since these are reserved characters for regex.
Does anybody knows a good subroutine that would escape nicely any of these characters for me so that later I could do something like:
$p_id =~ /^$key/
Solution. Use a substitution to backslash or double each character to be escaped.
The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.
$p_id =~ /^\Q$key\E/;
From your description, it sounds like you have it backwards. You do not need to escape the characters on the string you are matching on ($p_id), you need to escape your match string '^$key'.
Given:
$p_id = '$key$^%*&#@^&%$blah!!';
Use:
$p_id =~ /^\$key/;
or
$p_id =~ /^\Q$key\E/;
The \Q,\E pair treat everything in between as literal. In other words, you don't want to look for the contents of the variable $key, but the actual string '$key'. The first example simply escapes the $.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With