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

How do I escape metacharacters in a user-defined string?

by Coyo (Initiate)
on Jul 08, 2000 at 02:07 UTC ( [id://21599]=perlquestion: print w/replies, xml ) Need Help??

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

I run the following script and get the following output: What am I doing wrong here?

- a confused canine.
bash-2.02$ perl $formula = $bit = '(4+5)'; if( $formula =~ /$bit/ ) { print "yeah\n"; } else { print "Oh no!\n"; } ^D Oh no!

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I escape metacharacters in a user-defined string?
by Ovid (Cardinal) on Jul 08, 2000 at 02:18 UTC
    This is an easy mistake to make. I've made it myself. Notice that in $bit, you have parentheses '()' and a plus '+'. What your regex is doing is trying to find one or more fours followed by one five. It then, if successful, would capture this to $1.

    The easiest way to deal with the is to use the "quote" metacharacters (\Q and \E) in the regex.

    $formula = $bit = '(4+5)'; if( $formula =~ /\Q$bit\E/ ) { print "yeah\n"; } else { print "Oh no!\n"; }
    This will work as you expect. However, you'll have to be careful. Here's a warning from perlop:
      You cannot include a literal $ or @ within a \Q sequence. An unescaped $ or @ interpolates the corresponding variable, while escaping will cause the literal string \$ to be inserted. You'll need to write something like m/\Quser\E\@\Qhost/.
Re: How do I escape metacharacters in a user-defined string?
by Perlmage (Acolyte) on Jul 11, 2000 at 10:11 UTC

    You could also use quotemeta(), which is how the \Q is implemented. Ie.,

    $formula = '(4+5)';
    $bit = quotemeta $formula;
    if ( $formula =~ /$bit/ ) {
      print "yeah\n"; 
    } else { 
      print "Oh no!\n"; 
    }
    
    This will handle literal '$' and '@'.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (6)
As of 2024-04-24 09:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found