Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

safe regex variables

by oconnelm (Initiate)
on Jul 06, 2001 at 01:34 UTC ( [id://94293]=perlquestion: print w/replies, xml ) Need Help??

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

Hi,

I have a pretty ugly text-processing question. I'm trying to match a string denoted as a boundary by MIME headers then use it as a variable to annotate the different sections of a multipart message. This would be fine, except for the fact that the boundary strings conatin lots of regular expression quantifiers and tend to look like

EB-002(.BhNa.RALxMe_ZRHLIBVcyn_4sgz+G(v

I tried backslashing the variable name for the boundary string like:

if (/^-+\$boundary/){<br>

but this never matched the following instances, although it did let me use the string without a bad regex error. Just for kicks, I also tried using a backslash on the input, since it has the same problematic characters, but it doesn't get evaluated as a regular expression, so that unsurprisingly had no effect.

My question then is "Is there a way to safely (and efectively) use strings that contain special regex characters as patterns to be matched, without knowing ahead of time when, where and which special characters will occur in the pattern?"



Thanks,
Mike O'Connell

Replies are listed 'Best First'.
Re: safe regex variables
by japhy (Canon) on Jul 06, 2001 at 01:39 UTC
      Aha! Exactly what I needed but couldn't find. Thanks very much. -Mike
Re: safe regex variables
by MeowChow (Vicar) on Jul 06, 2001 at 06:28 UTC
    Your question has already been answered, but I have the feeling that you'll save yourself a lot of time if you check out MIME::tools, or perhaps MIME::Lite, if you haven't already. As we love to say around here, don't reinvent the wheel, use CPAN.
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
Re: safe regex variables
by srawls (Friar) on Jul 06, 2001 at 03:34 UTC
    Japhy already answered your question, but I thought I'd add that when you write this:
    if (/^-+\$boundary/){
    It means to match a literal $ sign, then the string 'boundary.' To do what you want, just do what japhy said and use:
    if (/^-+\Q$boundary\E/){
    (or you can use quotemeta on $boundary)

    The 15 year old, freshman programmer,
    Stephen Rawls

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2024-04-26 02:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found