Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Using string literal in regexp

by tomazos (Deacon)
on Jun 16, 2006 at 15:52 UTC ( #555824=perlquestion: print w/replies, xml ) Need Help??

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

I have a scalar string..

my $foo = '$@!#@#$^$#@^';

..and I want to incorporate it into a regular expression such that the characters of the string will be matched literally, no matter what characters they are.

ie

my $bigfoo='aabbaaa$@!#@#$^$#@^bbabaaba'; assert $bigfoo =~ /(a|b)*$foo(a|b)*/;

What is the correct way to interpolate a string literal into a regular expression?

Thanks,

-Andrew.

Replies are listed 'Best First'.
Re: Using string literal in regexp
by davorg (Chancellor) on Jun 16, 2006 at 15:55 UTC

    quotemeta or \Q ... \E.

    my $bigfoo=quotemeta('aabbaaa$@!#@#$^$#@^bbabaaba'); assert $bigfoo =~ /(a|b)*$foo(a|b)*/;

    or

    my $bigfoo='aabbaaa$@!#@#$^$#@^bbabaaba'; assert $bigfoo =~ /(a|b)*\Q$foo\E(a|b)*/;
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Using string literal in regexp
by sh1tn (Priest) on Jun 16, 2006 at 17:43 UTC
    You should use qr operator.
    If the character is special one, escape it with '\'.
    You may want to read this manual - perlre


      I don't think this is helpful.

      How does qr// help? Interpolation happens there too!

      How do you perform generalized backslash escaping on an arbitrary string? Do you run it through another regex first? Do you recreate the behavior of quotemeta or \Q...\E then, perhaps badly?

      davorg has given far better advice.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://555824]
Approved by idsfa
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2023-12-06 18:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?











    Results (31 votes). Check out past polls.

    Notices?