RegEx Problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jerry Baker

    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

    #2
    Re: RegEx Problem

    Jerry Baker wrote:[color=blue]
    > How can I tell Perl to ignore "special" characters in a variable when
    > performing a RegExp comparison?[/color]

    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-----

    Comment

    Working...