Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Regex help

by bingohighway (Acolyte)
on May 06, 2009 at 11:06 UTC ( [id://762220]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks,

I have a bit more of a complicated regex which I am stuck with. User types in the string to be matched, e.g. toilet(32), and this should then be whacked into a regex to match to a variable.

I know the brackets are causing a problem, so the input string should go from /toilet(32)/ to this /toilet\(32\)/so the regex can function properly. Can anyone help me witha substitution regex to scan this string and prepend all non-complying characaters with "\".

Also, some of the strings will actually be some code, with the regex inside.e.g.

$line = 'if($appliance =~ /toilet(32)/)';
Should be:
$line = 'if($appliance =~ /toilet\(32\)/)';
If that makes sense :-) Cheers

Replies are listed 'Best First'.
Re: Regex help
by Anonymous Monk on May 06, 2009 at 11:12 UTC
      ... or /\Q$variable\E/ (which uses quotemeta under the hood)
        What is the reason to put \E at the end of a regexp?
      Is there a way of running quotemeta between bounds however, e.g.
      $line = 'if($appliance =~ /toilet(32)/)';
      Should be:
      $line = 'if($appliance =~ /toilet\(32\)/)';
      In a simple one-liner?

      Cheers!

      Superb :-) It's amazing the little jewels Perl has hidden away.
Re: Regex help
by JavaFan (Canon) on May 06, 2009 at 11:36 UTC
    Why use a regexp in that case? index will do as well.
Re: Regex help
by planetscape (Chancellor) on May 07, 2009 at 03:32 UTC
Re: Regex help
by vinoth.ree (Monsignor) on May 06, 2009 at 13:19 UTC
    quotemeta is the best way to do this

    If u want to this by the explicitly instead of using the quatemeta just add the character you want to prefix with the "\" in the substitute.

    while(<>){ $_=~ s/([\$|\||\[|\)|\\|\/|\(])/\\$1/g; print; }
    Vinoth,G
      How about reading a string, searching for the regex (i.e. encased by /$regex/) and only doing this substitution within the regex delimeters? Cheers!
Re: Regex help
by bichonfrise74 (Vicar) on May 06, 2009 at 22:57 UTC
    I really like quotemeta.

Log In?
Username:
Password:

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

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

    No recent polls found