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

Discussion in 'Perl Misc' started by PerlFAQ Server, Jan 25, 2011.

  1. 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
    string.

    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
    perlfaq.pod.
    PerlFAQ Server, Jan 25, 2011
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    3
    Views:
    13,101
  2. Stimp
    Replies:
    2
    Views:
    2,222
    Stimp
    Sep 20, 2006
  3. Eric Layman
    Replies:
    3
    Views:
    605
    Rad [Visual C# MVP]
    Apr 14, 2007
  4. Replies:
    6
    Views:
    428
    Stefan Ram
    Jun 15, 2008
  5. PerlFAQ Server
    Replies:
    10
    Views:
    181
    ccc31807
    Apr 13, 2011
Loading...

Share This Page