Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape special chars in a string I interpolate into a Perl regex?

Tags:

regex

perl

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/
like image 902
goe Avatar asked Jan 28 '10 18:01

goe


People also ask

How do you escape a special character in Perl?

Solution. Use a substitution to backslash or double each character to be escaped.

How do you escape a string in regex?

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.


2 Answers

$p_id =~ /^\Q$key\E/;
like image 192
ЯegDwight Avatar answered Sep 27 '22 19:09

ЯegDwight


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

like image 40
Jeff B Avatar answered Sep 27 '22 20:09

Jeff B