while ( ) { if ( /^(\d+\/123 11.*?)(?= a )(?:.*?zyx(.*))?/ ) { print "THIS IS THE FIRST MATCH: $1" ,$/; print "THIS IS THE SECOND MATCH: $2" ,$/ if defined $2; } } __DATA__ 12/123 11-abc 456 a 1/2 zyx this is the last 1 13/123 11-abc 456 a 1/2 zyx this is the last 2 14/456 11-abc 456 a 1/2 zyx this is it 15/456 11-abc 456 a 1/2 zyx this is it 16/123 11-abc 456 a 1/2 zyx this is the last 3 17/123 11-abc 456 a 1/2 xyz this is the last 3