Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Make a variable safe for a regex.

by jettero (Monsignor)
on Feb 25, 2007 at 21:56 UTC ( [id://602051]=note: print w/replies, xml ) Need Help??


in reply to Make a variable safe for a regex.

You want \Q and \E as indicated on perlre. They're perhaps a little obscure and arcane, but powerful and awesome.

$Title =~ s,^\Q$Artist\E\s*-\s*,,ig;

-Paul

Replies are listed 'Best First'.
Re^2: Make a variable safe for a regex.
by exodist (Monk) on Feb 25, 2007 at 22:27 UTC
    \Q and \E worked, thanks a lot!
Re^2: Make a variable safe for a regex.
by Sixtease (Friar) on Feb 28, 2007 at 22:15 UTC
    Is there a way to do this for UTF-8 strings too? \Q will break multi-byte characters.

      Can you supply a test case for that? I've tried (shortly) and it seems to work for me:

      C:\>perl -le "my $str = qq(foo\x{100}bar); my $re = qr/^\Q$str\E/; war +n $str; warn $re; warn $str =~ /$re/;" foo─Çbar at -e line 1. (?-xism:^foo─Çbar) at -e line 1. 1 at -e line 1.

      Maybe it fails for some other cases of unicode chars, and if so I'd consider that a bug.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-23 23:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found