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

Is there a simple way to quote strings in regexps so that it is not necessary to escape individual special characters? For example, if I have a fragment of code like this:
my $string = 'Some text with $ signs in it'; my $pattern = '$ signs'; $string =~ s/$pattern/dollar signs/; print "$string\n"
in which $pattern could contain characters with special regexp meanings is there a way to make this work "sensibly" without using one or more previous regexps to escape all the special characters (ie in this case convert $pattern to '\$ signs').

Replies are listed 'Best First'.
Re: Quoting strings in regexps
by japhy (Canon) on Jul 19, 2002 at 19:07 UTC
    Simply use the \Q escape.
    if ($str =~ /\Q$pat/) { ... } if ($str =~ /.\Q$pat\E./) { ... }

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;