Capturing optional string using perl regex -


i trying parse strings have pattern

src [interface_name:source_address[/source_port]]  

where parts in brackets optional. there 3 possible variants

src src lan:10.115.1.204 src lan:10.115.1.204/8080 

i want capture interface, source ip , source port string.

my regex third variant

($srcinterface,$srcip,$src_port) = m/^src (.*?):(.*?)\/(.*?)/; 

but don't know how make regex works 3 variants.

edit bigger part of problem src dst information being received system , need repeat regex. see below strings:-

src dst outside:125.22.32.192 src outside:182.201.183.178 dst outside:125.22.32.192 src outside:182.201.183.178/5525 dst outside:125.22.32.192/8595 

use instead:

/^src(?> (\w++):((?>[0-9]{1,3}\.){3}[0-9]{1,3})(?>\/([0-9]++))?)?/ 

an example script:

#!/usr/bin/perl  use strict;  $str = "src src lan:10.115.1.204 src lan:10.115.1.204/8080"; $i = 0; while($str =~ /^src(?> (\w++):((?>[0-9]{1,3}\.){3}[0-9]{1,3})(?>\/([0-9]++))?)?/gm) { print "\n[match " . ++$i . "]"     . "\nwhole match    : $&"     . "\ncapture group 1: $1"     . "\ncapture group 2: $2"     . "\ncapture group 3: $3\n"; } 

for more permissive pattern, can use this:

/^src(?> (\w++):([^\/\n]++)(?>\/([^\n]++))?)?/gm 

or this:

/^src(?> (\w++):([^\/\n]++)(?>\/(\s++))?)?/gm 

the idea these pattern use negated character classes, example [^\/\n] means all characters not slash or newline. can adapt these classes needs adding or removing characters.


Comments