moked has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm trying to use regexp on two string from txt files in the next method:
$a =~ /$b/;
$a and $b are origin in an external txt file an might contain "special" characters.
(characters like "+","*","[")
When that happens the script will return an error and die.
I did not find help in the documentation for this possibility.

please advise

Nir Moked

Replies are listed 'Best First'.
Re: special characters in regexp
by ikegami (Patriarch) on Jun 21, 2010 at 05:25 UTC

    Does $a match the regex pattern in $b?

    $a =~ /$b/

    Does $a contain the string in $b?

    $a =~ /\Q$b\E/ $a =~ /\Q$b/ # \E is optional my $b_re = quotemeta($b); # This is what \Q does $a =~ /$b_re/

    Does $a equal the string in $b?

    $a eq $b $a =~ /^\Q$b\E\z/ my $b_re = quotemeta($b); $a =~ /^$b_re\z/

    quotemeta

Re: special characters in regexp
by SuicideJunkie (Vicar) on Jun 21, 2010 at 13:33 UTC

    First, avoid using $a and $b; they're special.

    If you are intending for $regexPattern to be a user supplied regex that may contain errors, then perhaps you want to *eval* the regex match and trap said errors.

    my $matched; my $contender = 'foo'; my $regexPattern = '+foo'; #won't work eval { $matched = $contender =~ /$regexPattern/ }; warn $@ if $@; print "Hey, did I survive the error? Yay!\n";
      First, $a and $b are probably just dummy variables to indicate the problem. And even if they do, most of the time, there's no problem at all when using $a and $b.

      But if we're nitpicking, if you shouldn't use a construct just because in some cases, this fails, you made a bigger boo-boo than the op with his $a and $b. You're trying to use $@ as an indication whether an eval failed or not. That's wrong; an eval may fail while $@ is false due to cleanup actions. The only way to be sure an eval succeeded is to check its return value:

      eval { $matched = $contender =~ /$regexPattern/; 1; } or warn $@ // "Unknown error";