#!C:/perl/bin -w my @testitems = qw( aaa_gjh1_dfgdf_0009 aaa_gjh_0000 aaa_gjh1_DFgdf_0009 aaa_fdsfs_000 aaa_sdf_jdsh_01111 aaa_gjh1_dfgdf_0009 aaa_gjhi0000 aaa_gjh1_df<:df_0009 aaa_gjh_0000 aaa_ABCDEFGHI123456789ZYXW_1111 aaa_ABCDEFGHI123456789ZYXWVUT_1111); # next to last: 23 before the last underline # last element: more than 24 intermediate chars for my $item(@testitems) { if ( $item =~ m/ ^aaa_ # starts with "aaa_" [_A-Za-z0-9]{1,23} # test next 1,23 chars: underline, alphas or decimal_nums (?<=\D) # Pos_LookBehind, Last char BEFORE last 4 (may be the 24th) # can't be a digit else we may find 5 digits at the end \d{4}$ # has ONLY - emphasis mine - four digits at the end /x ) { print "MATCHES: $item\n"; } else { print "NO match: $item\n"; } } print "done\n"; =head1 OUTPUT: MATCHES: aaa_gjh1_dfgdf_0009 MATCHES: aaa_gjh_0000 MATCHES: aaa_gjh1_DFgdf_0009 # caps are alpha; OP may want only lc NO match: aaa_fdsfs_000 # only 3 digits at end of string # (contrary to spec) NO match: aaa_sdf_jdsh_01111 # 5 digits at end of string # (contrary to spec) MATCHES: aaa_gjh1_dfgdf_0009 MATCHES: aaa_gjhi0000 # no underscore before final 4 digits # (ok per spec) NO match: aaa_gjh1_df<:df_0009 # includes symbol and punct # (contrary to spec) MATCHES: aaa_gjh_0000 MATCHES: aaa_ABCDEFGHI123456789ZYXW_1111 # < 24 chars before final 4 digits # (ok per spec) NO match: aaa_ABCDEFGHI123456789ZYXWVUT_1111 # > 24 chars before final 4 digits # (contrary to spec) done =cut