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

Hi,

I've got a regular expression query...

Is it possible to "automatically" backslash the regex "special" characters if they appear in a term?
Example:
I have a record that looks like such: "A random record + stuff".
when i do a regex on that record i would need to \ the +.
If I have a bunch of records that could possilbe contain any character, I would have to do that for every character that could cause a problem.
I would like to know if there is an "easier" way than =~ s/\+/\\\+/g; for every "special" character?
Cheers,
Reagen

Replies are listed 'Best First'.
Re: regex special chars
by dragonchild (Archbishop) on May 27, 2004 at 13:44 UTC
    Wrap it in \Q and \E. So, for example, if you wanted to match a +, you could do /\Q+\E/

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

      Thanks.
Re: regex special chars
by Roy Johnson (Monsignor) on May 27, 2004 at 13:45 UTC
    /\Q$literal_string\E/
    See perldoc -f quotemeta

    The PerlMonk tr/// Advocate
Re: regex special chars
by Ven'Tatsu (Deacon) on May 27, 2004 at 13:45 UTC
    You can use /\Q$patern_to_match_literaly\E/
    from the perlre man page:
    \E end case modification (think vi)
    \Q quote (disable) pattern metacharacters till \E
      I love perlmonks.

      Thanks guys :)
Re: regex special chars
by matsmats (Monk) on May 27, 2004 at 13:50 UTC

    Read up on the function quotemeta.

    Alternatively, wrap it with \Q$regexp\E in your regexp like this:

    my $text = 'foo bar + \wbaz'; my $re = ' + \w'; if ($text =~ /(\Q$re\E)/) { print $1; } else { warn "nothing found\n"; }

    That goes for the same as quotemeta does, just for the regexp.

    Mats