Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

How do I escape meta-characters in a user-defined string?

by Kozz (Friar)
on Mar 25, 2000 at 00:49 UTC ( #6100=perlquestion: print w/replies, xml ) Need Help??

Kozz has asked for the wisdom of the Perl Monks concerning the following question: (regular expressions)

In the example below, the results are I found a match: "a" I found a match: "b" There was no match for "a+b" Now, the problem is that the + in the third key of the hash is being interpreted as a description of the regular expression, not as a literal character. If I have a large hash which contains these types of meta-characters in the keys, how do I escape those meta-characters to prevent them being interpreted?
#!/usr/bin/perl my %hash=( 'a', '2', 'b', '5', 'a+b', '7', ); my $string='a+b'; my $key; foreach $key (keys %hash){ if($string=~/$key/){ print "I found a match: \"$key\"\n"; }else{ print "There was no match for \"$key\"\n"; } }

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I escape meta-characters in a user-defined string?
by btrott (Parson) on Mar 25, 2000 at 01:05 UTC
    if($string=~/\Q$key\E/){
    Quotes the metacharacters.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://6100]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2022-05-19 16:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (72 votes). Check out past polls.

    Notices?