tags:

views:

80

answers:

2

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/
+5  A: 
$p_id =~ /^\Q$key\E/;
RegDwight
What does \Q and \E do?
goe
Quote and endquote. It means that $key is treated as a string with no special characters.
Evan
@goe, they quote the metacharacters.
daotoad
Thanks, that works!
goe
This is the same as calling `quotemeta($key)`
Brad Gilbert
+5  A: 

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 $.

Jeff B