my @matches = $string =~ / ^ # beginning of line (\d{1,5}) # 1-5 digit number \s+ # gap (?: # group ([A-Z0-9()-]{7}) # 7-char thing \s+ # gap ([A-Z0-9()-]{7}) # another 7-char thing ){1,45} # 7-char thing # up to 45 groups $ # end of line /gx; my $first = shift @matches; my $count = 1; while (@matches) { print $first, ' ', $count, ' ', shift @matches, ' ', shift @matches, "\n"; $count++; }