in reply to Re: Extract a pattern from a string
in thread Extract a pattern from a string

Hi
The BIG picture is very simple
i have a list of strings like i showed
ME170-5/2/8-ME172-2/2/6-ME4028
ME172-2/1/2-ME196-1/1/3-ME4002
i need to extract from each string the port numbers ie 5/2/8 or 2/2/6 etc..
then according to an index of a number found in the string
i need to select the port with the correct index number.
for example with the strings above.
string 1 = ME170-5/2/8-ME172-2/2/6-ME4028
string 2 = ME172-2/1/2-ME196-1/1/3-ME4002
if my search number is 172 then for
string 1 i would get 2/2/6
and for string 2 i would get 2/1/2
thank you
Avi

Replies are listed 'Best First'.
Re^3: Extract a pattern from a string
by avim1968 (Acolyte) on Jun 10, 2012 at 11:56 UTC
    After reading all the answers in this topic i have managed
    to create my Perl code to do just what i need
    Thank you ALL :-)
    Avi
Re^3: Extract a pattern from a string
by AnomalousMonk (Archbishop) on Jun 10, 2012 at 17:15 UTC

    If knowing the position of the port number in the string is necessary in order to be able to work your way back to and extract the index number, there's a more direct way:

    >perl -wMstrict -le "my $dd = qr{ \d{1,2} }xms; ;; my %indices; for my $s ( 'ME170-5/2/8-ME172-2/2/6-ME4028-FOO172-222/2/666-BAR', 'ME172-2/1/2-ME196-1/1/33-ME4002-11/2/3-ME1-1/22/3-ME22', '1-1/2/3', 'ME-9/9/9-ME', ) { push @{ $indices{$1} }, $2 while $s =~ m{ (\d+) - ($dd (?: / $dd){2}) }xmsg; } ;; for my $i (sort { $a <=> $b } keys %indices) { printf qq{index '$i': port(s) '%s' \n}, join q{' '}, @{ $indices{$i} }; } " index '1': port(s) '1/22/3' '1/2/3' index '170': port(s) '5/2/8' index '172': port(s) '2/2/6' '2/1/2' index '196': port(s) '1/1/33' index '4002': port(s) '11/2/3'