开发者

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

I have a string which may hold special char开发者_运维百科acters 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/


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜