Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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

by Coyo (Initiate)
on Jul 08, 2000 at 02:07 UTC ( #21599=categorized question: print w/replies, xml ) Need Help??
Contributed by Coyo on Jul 08, 2000 at 02:07 UTC
Q&A  > regular expressions


Description:

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!

Answer: How do I escape metacharacters in a user-defined string?
contributed by Ovid

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/.
Answer: How do I escape metacharacters in a user-defined string?
contributed by Perlmage

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 '@'.

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    [LanX]: Choroba: do you miss chaos with ties? apply at the US government.. ;)
    [ambrus]: Corion: those are good rules.
    [ambrus]: Discipulus: oh sure. the input data has different filenames every time I get them.
    [ambrus]: the directory structure may be 1, 2, or 3 deep, it may have spaces in the filename or not, it has dates in various format, different keywords for the same meanings, and the dates and other keywords are assembled in various ways.
    [Discipulus]: no ambrus by specification i mean for example license per core instead of per socket, so fields are different

    How do I use this? | Other CB clients
    Other Users?
    Others rifling through the Monastery: (14)
    As of 2017-03-29 12:12 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      Should Pluto Get Its Planethood Back?



      Results (350 votes). Check out past polls.