use warnings; use strict; while(){ print if / cat # word cat (?: # do not capture (?! # negative lookahead \s* # possible whitespace dog # the word dog ) # end negative lookahead ) # end do not capture group /x; # /cat(?:(?!\s*dog))/ } __DATA__ my cat loves dogs catdog cat dog dog dog dog cat dog dog cat not a dog