#! /usr/bin/perl use strict; use warnings; use 5.010.000; my $re = qr{ ^(\d{9}) # save in $1 :\s # fixed string (?: # group without saving .*? # any string, as short as possible (H\d{9}) # save in $2 )? # the "not-saving" group is optional (for lines without matching the pattern for $2) }x; while ( my $line = ) { if ( $line =~ $re ) { # print line numbers and matches printf "%d : \$1 = %s; \$2 = %s\n", $., ( $1 // '' ), ( $2 // '' ); } } __DATA__ 410304100: 410304100 410304101 410304100: H410304100 410304101 410304100: 410304100 H410304101