# always match the entire string, running your code on matching lines /^(?: (?: ([AB]) (.+) (?{ print "$1 method $2\n"; }) | .* ) \n? )*/x