Regex with backslash in string?

E

el_roachmeister

I am trying to perform a regex on a string that contains a backslash. I
need the backslash in the string but I want to somehow escape it in the
regex. Can this be done? I have posted the code below which outputs
"Not Matched".

#!/usr/bin/perl

use warnings;
use strict;

my $name = 'John \ 123'; # backslash in name causes problem
my $test = $name;

if ($name =~ /$test/) {print 'Matched';}
else { print 'Not Matched';}
 
L

Lars Eighner

In our last episode,
the lovely and talented (e-mail address removed)
broadcast on comp.lang.perl.misc:
I am trying to perform a regex on a string that contains a backslash. I
need the backslash in the string but I want to somehow escape it in the
regex. Can this be done? I have posted the code below which outputs
"Not Matched".

Examples of how to match a backslash are found in perlrequick,
perlretut, and perlre -- or in other words, in every section of
the documentation that deals with regular expressions.

#!/usr/bin/perl
use warnings;
use strict;
 
E

el_roachmeister

I do know how to escape a backslash but I am trying to escape a string
that contains a backslash. Is that possible?
 
G

Gunnar Hjalmarsson

I am trying to perform a regex on a string that contains a backslash. I
need the backslash in the string but I want to somehow escape it in the
regex. Can this be done?

perldoc -q "quote a variable"
 
T

Tad McClellan

I am trying to perform a regex on a string that contains a backslash. I
need the backslash in the string but I want to somehow escape it in the
regex. Can this be done?


Your Question is Asked Frequently:

perldoc -q regex

How can I quote a variable to use in a regex?


You are expected to check the Perl FAQ *before* posting to
the Perl newsgroup.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,991
Messages
2,570,217
Members
46,805
Latest member
ClydeHeld1

Latest Threads

Top