FAQ 6.9 How can I quote a variable to use in a regex?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This is an excerpt from the latest version perlfaq6.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


6.9: How can I quote a variable to use in a regex?

    The Perl parser will expand $variable and @variable references in
    regular expressions unless the delimiter is a single quote. Remember,
    too, that the right-hand side of a "s///" substitution is considered a
    double-quoted string (see perlop for more details). Remember also that
    any regex special characters will be acted on unless you precede the
    substitution with \Q. Here's an example:

            $string = "Placido P. Octopus";
            $regex  = "P.";

            $string =~ s/$regex/Polyp/;
            # $string is now "Polypacido P. Octopus"

    Because "." is special in regular expressions, and can match any single
    character, the regex "P." here has matched the <Pl> in the original

    To escape the special meaning of ".", we use "\Q":

            $string = "Placido P. Octopus";
            $regex  = "P.";

            $string =~ s/\Q$regex/Polyp/;
            # $string is now "Placido Polyp Octopus"

    The use of "\Q" causes the <.> in the regex to be treated as a regular
    character, so that "P." matches a "P" followed by a dot.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Site Timeline