# Untested my $ScanString =~ / ( # start of capture INSERT .*? # the ? after * means the shortest possible match ) # end of capture (?:\(|values|select|;) # (?: thing ) groups without capturing /six; # s allows .* to match across several lines. x allows spaces and comments in the regex my $substring = $1; my $found_doc = $substring =~ /\b doc \b/ix; # \b means boundary, so beginning or end of a word