RegEx Problem

J

Jerry Baker

Special characters inside of variables cannot be escaped, but Perl tries
to use them in a RegEx. Try this example program to see what I mean:

-----PROGRAM-----
#!/usr/bin/perl

$test = "This + test";
$test2 = "+";
if($test =~ /^This $test2 test$/) {
print "WORKS!!!";
}
else {
print "DOESN'T WORK";
}
-----PROGRAM-----

The result will always be "DOESN"T WORK". The same result will occur if
you change $test2 = "\+".

To verify that the program isn't at fault, the following always returns
"WORKS!!!":

-----PROGRAM-----
#!/usr/bin/perl

$test = "This + test";
if($test =~ /^This \+ test$/) {
print "WORKS!!!";
}
else {
print "DOESN'T WORK";
}
-----PROGRAM-----

How can I tell Perl to ignore "special" characters in a variable when
performing a RegExp comparison?

Thanks.
 
J

Jerry Baker

Jerry said:
How can I tell Perl to ignore "special" characters in a variable when
performing a RegExp comparison?

The answer is \Q and \E.

-----PROGRAM-----
#!/usr/bin/perl

$test = "This + test";
$test2 = "+";
if($test =~ /^This \Q$test2\E test$/) {
print "WORKS!!!";
}
else {
print "DOESN'T WORK";
}
-----PROGRAM-----
 

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

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top