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

hi monks!

i have a question regarding regular expressions

im using net::pcap to capture packets, and when I get a result I want to act differently depending on what protocol the packet is in. Specifically, I'm dealing with Voip. And as some of you will know, it doesn't support listing protocols as 'rtp sip and sdp'.

so my solution was to look at the packets themselves (which appear to me as large individual strings), and if they contained certain words, act on them like that

I want to construct a regex for each circumstance, but am having problems digesting the documentation i can find..! There's millions of examples, but can't find one that seems appropriate for me. can someone please help to suggest an alternative? the logic was..

to find a SIP packet: if (packet_string contains the word 'sip' but NOT the word 'sdp') { print "packet appears to be sip"; }
to find a SDP packet: if (packet_string contains the word 'sip' and ALSO CONTAINS the word ' +sdp) { print "packet appears to be sdp"; }
to find an RTP packet: if (packet_string cotains NEITHER 'sdp and sdp') { print "packet appears to be rtp"; }

I currently try to achieve this by doing the following code. but it unfortunatly isn't quite achieving what I need.

if ($packet !~ m/sip && sdp/) { print "packet is RTP\n"; } elsif ($packet =~ m/sip/g) { print "packet is sip\n"; } elsif ($packet =~ m/sdp/ && m/sip/) { print "packet is sdp!\n"; }

thanks if anyone can help...!

bigmoose

Replies are listed 'Best First'.
Re: help defining regular expressions
by BrowserUk (Patriarch) on Dec 14, 2011 at 09:44 UTC

    You cannot use && inside a regex. But you can use it outside:

    if( $packet !~ m/sip/ && $packet !~ m/sdp/ ) { print "packet is RTP\n"; } elsif( $packet =~ m/sip/ ) { if( $packet =~ m/sdp/ ) { print "packet is sdp\n"; } else { print "packet is sip!\n"; } }

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

      wow thanks!

      you've opened my eyes! :) +rep

      moose

Re: help defining regular expressions
by pvaldes (Chaplain) on Dec 14, 2011 at 23:57 UTC

    There is still some room to improve. A more compact version of the former code.

    my $type = 'unknown/malformed'; if($packet =~ m/sip/i) { if ($packet =~ m/sdp/i){$type='sdp'} else {$type='sip'} } else ($packet !~ m/s[id]p/i) {$type ='RTP'} print "packet is of type ", $type, "\n";