Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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

by Ovid (Cardinal)
on Jul 08, 2000 at 02:18 UTC ( #21600=categorized answer: print w/replies, xml ) Need Help??

Q&A > regular expressions > How do I escape metacharacters in a user-defined string? - Answer 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/.

Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2017-05-22 22:40 GMT
Find Nodes?
    Voting Booth?