use 5.010; # need (?|pattern) "branch reset" regex construct use strict; use warnings; my $result = <<'EOT'; transaction 1234567; promote; 2014/08/01 10:22:37 ; user: john # Performing a "promote" on file. /./abc/desf/test.pl 138699/1 (138700/1) transaction 4578643; promote; 2014/08/01 10:22:37 ; user: sam /./abc/desf/test.pl 138699/1 (138700/1) EOT print qq{[[$result]] \n\n}; while ($result =~ m{ transaction \s (\d+) .*? user: \s* (\S+) \s* (?| [#] \s* ([^\n]*) | ()) # comment or empty string to $3 }xmsg) { my ($transaction, $user, $comment) = ($1, $2, $3); printf "%-12s %-10s %s\n", $transaction, $user, $comment; }