>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'