Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > RegEx Problem

Reply
Thread Tools

RegEx Problem

 
 
Jerry Baker
Guest
Posts: n/a
 
      06-21-2006
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.
 
Reply With Quote
 
 
 
 
Jerry Baker
Guest
Posts: n/a
 
      06-21-2006
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

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

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How make regex that means "contains regex#1 but NOT regex#2" ?? seberino@spawar.navy.mil Python 3 07-01-2008 03:06 PM
String Pattern Matching: regex and Python regex documentation Xah Lee Java 1 09-22-2006 07:11 PM
Is ASP Validator Regex Engine Same As VS2003 Find Regex Engine? =?Utf-8?B?SmViQnVzaGVsbA==?= ASP .Net 2 10-22-2005 02:43 PM
Java regex imposture re: Perl regex compatibility a_c_Attlee@yahoo.com Java 2 05-06-2005 12:16 AM
perl regex to java regex Rick Venter Java 5 11-06-2003 10:55 AM



Advertisments