use warnings; use strict; while () { chomp; next if ! /^ (\d+)\s # Capture the number (?: # Start of non-capture group MatchMe\s\[(?=.*\]$) # Match matchme [.*] | I\sneed\sto\sbe\sdispatched.*\:\s(?=[^\]]*$) ) (.*?)\]?$/x; #capture reason print "Line $1, reason: $2\n"; } __DATA__ 111 MatchMe [This is why] 222 I need to be dispatched to the same callback: For This Reason 112 MatchMe [This is why 223 I need to be dispatched to the same callback: For This Reason] #### Line 111, reason: This is why Line 222, reason: For This Reason