RegEx Problem

Discussion in 'Perl' started by Jerry Baker, Jun 21, 2006.

  1. Jerry Baker

    Jerry Baker Guest

    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, Jun 21, 2006
    #1
    1. Advertising

  2. Jerry Baker

    Jerry Baker Guest

    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-----
     
    Jerry Baker, Jun 21, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?SmViQnVzaGVsbA==?=

    Is ASP Validator Regex Engine Same As VS2003 Find Regex Engine?

    =?Utf-8?B?SmViQnVzaGVsbA==?=, Oct 22, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    745
    =?Utf-8?B?SmViQnVzaGVsbA==?=
    Oct 22, 2005
  2. Rick Venter

    perl regex to java regex

    Rick Venter, Oct 29, 2003, in forum: Java
    Replies:
    5
    Views:
    1,693
    Ant...
    Nov 6, 2003
  3. Replies:
    2
    Views:
    628
  4. Xah Lee
    Replies:
    1
    Views:
    972
    Ilias Lazaridis
    Sep 22, 2006
  5. Replies:
    3
    Views:
    832
    Reedick, Andrew
    Jul 1, 2008
Loading...

Share This Page