my $data = ' Timed out (reason: in while loop) ::expect_out(0,string) = > ::expect_out(1,string) = RF use CSWT#RF### dis qremote(MQSI.3PL846) RNAME1 : dis qremote(MQSI.3PL846) RNAME AMQ8409: Display Queue details.QUEUE(MQSI.3PL846)TYPE(QREMOTE)RNAME(MQSI.3PL846) No commands have a syntax error. AMQ8409: Display Queue details.QUEUE(MQSI.3PL944)TYPE(QREMOTE)RNAME(MQSI.3PL944) end2 : end '; my $match = qr {(?mx) ^ AMQ8409 .+ (QUEUE\([^)]+\)) .+ (RNAME\([^)]+\)) }; for ( split /\n/, $data ) { print "$1 ----> $2\n" if /$match/ }