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

Hi, I am working on a traceroute script which would do tracerouting to certain hosts and save the result in xml. Unfortunately i am stuck with something which seems to be easy. The left side looks like this: mydomain.com [192.168.242.2] and the right side is only the ip 192.168.242.2 Unfortunately i dont get a match unless i add square parantheses around so below is a match but if i take the square paranthes away its not. I tried to change the left side to \Q$tempreg\E in order to escape the bloody paranthesis but it doesnt work anyway.
my $tempreg = $p->get_token()->raw; #yes i checked it my $tempreg2 = $Tracearray[$snr][1]; if ("$tempreg" =~ m/[192.168.242.2]/) { print "finally a match"; }
Any ideas?
/Alexander

Replies are listed 'Best First'.
Re: regexp problem, square parentheses ("brackets")
by liverpole (Monsignor) on Feb 18, 2007 at 18:06 UTC
    Hi alex452,

    First of all, please wrap your code in <code> ... </code> tags, so that it's easier to read.

    Secondly, I think what you're looking for is to "escape" the brackets [ ... ] within your regular expression.  So perhaps you want something like the following ...?

    my $tempreg = $p->get_token()->raw; if ($tempreg =~ /\[192\.168\.242\.2\]/) { print "finally a match\n"; }

    You can read more about regular expressions in perlrequick, perlretut, or perlre, where you'll see that the bracket characters [ ... ] are "metacharacters" with special meaning (specifically, they delimit "character classes"), so you have to put backslashes in front of any to search for them like other, non-special characters.  The same thing is also true of periods ".", which when unescaped, match any character except newline, and must therefore also be escaped with "\".


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: regexp problem, square paranthesis
by andyford (Curate) on Feb 18, 2007 at 18:12 UTC
      Hi Andy, Thanks for the tip, i guess i will use it, but the way i look at this, its handling of the output which is more important here. Hi Liverpole, thanks for the tip, i solved it now. i esacped the dots on the right side and it works now. the funny thing i tried that before together with \Q and \E on the left side but that didnt work.
Re: regexp problem, square paranthesis
by johngg (Canon) on Feb 18, 2007 at 18:28 UTC
    You might like to have a look at Writeup Formatting Tips to help you format your posts the way you want. Specifically, you can use &#91; to get a [ and &#93; to get a ].

    Cheers,

    JohnGG