18

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/
brian d foy
  • 129,424
  • 31
  • 207
  • 592
goe
  • 5,207
  • 14
  • 45
  • 49
  • Duplicate: http://stackoverflow.com/questions/2135519/why-does-my-regular-expression-fail-with-certain-substitutions – Sinan Ünür Jan 28 '10 at 19:25
  • 1
    possible duplicate of [How do I handle special characters in a Perl regex?](http://stackoverflow.com/questions/576435/how-do-i-handle-special-characters-in-a-perl-regex) – daxim Mar 25 '11 at 14:33

2 Answers2

30
$p_id =~ /^\Q$key\E/;
ЯegDwight
  • 24,821
  • 10
  • 45
  • 52
6

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
  • 29,943
  • 7
  • 61
  • 90