use warnings; use strict; my $find = qr/ ^ # start of string \w+ # one or more word chars (last name) \s+ # one or more whitespace ( # begin capture (goes into $1) (?:H0|HT) # H0 or HT .* # everything to end of string ) # end capture /x; open my $fh, '<', 'in.txt' or die $!; while (<$fh>){ if (/$find/){ my $string = $1; # $1 contains what we captured in the rex print "$string\n"; } } #### HT00000000 I HT00000000 S HT00000000 I HT00000000 M HT00000000 I HT00000000 I H000000000 I H000000000 O H000000000 I