use strict; use warnings; while ( my $string = ) { my $found = ''; my $count = 0; chomp $string; if ( $string =~ /(5163)/g ) { $found .= $1; while ( $string =~ /([\d ])/g and $count < 8 ) { $found .= $1; if( $1 =~ /\d/ ) { $count++; } } } print +($count == 8 ) ? "$string\t=>\t$found\n" : "$string\t\tFAILED:\ttoo few digits matched\n"; } __DATA__ abcdef 5163 1234 5678 1234516323493293 12345163234932934567890 12345163234567