Go Back   Velocity Reviews > Newsgroups > PERL
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Reply

PERL - RegEx Problem

 
Thread Tools Search this Thread
Old 06-21-2006, 05:31 PM   #1
Default RegEx Problem


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.


Jerry Baker
  Reply With Quote
Old 06-21-2006, 06:01 PM   #2
Jerry Baker
 
Posts: n/a
Default Re: RegEx Problem

Jerry Baker wrote:
> 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-----
  Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump