$ perl -le'my $x = "A B C\nA B D\n"; print "exactly two matches" if $x =~ /^ [^A]* A [^A]* A [^A]* $/xg' exactly two matches