Regular Expression AND NOT: How to Require and Exclude Terms
How to express AND and NOT in regular expressions with lookaheads, where the patterns break, which engines support them, and when separate plain checks are better.
Regular expressions have a built-in OR, the pipe character, but no AND or NOT operator. To say "this line contains one term but not another," you need lookahead assertions, a rewritten pattern, or more than one test. This review explains how each approach works, where it fails, and when plain code or chained commands are the better choice.
Is a single AND NOT pattern right for your use?
Use a single pattern when the destination accepts only one regex, such as a search box, a validation field, a log filter, or a configuration setting. That is the main benefit: one string does all the work. The tradeoff is that the pattern depends on lookahead support and becomes harder to read with every condition you add. Use separate plain checks instead when you are writing code anyway, when the engine has no lookaround, or when people who do not work with regex regularly will maintain the result.
What the pattern actually does
AND and NOT are built from zero-width lookahead assertions. A positive lookahead, (?=...), succeeds if its contents could match from the current position. A negative lookahead, (?!...), succeeds if they could not. Neither one consumes characters. Several lookaheads can therefore sit at the same anchor, and each one checks the text independently.
Contains both "apple" and "banana", in any order:
^(?=.*\bapple\b)(?=.*\bbanana\b)
Does not contain "cherry":
^(?!.*\bcherry\b)
Contains "apple" but not "cherry":
^(?=.*\bapple\b)(?!.*\bcherry\b)
These patterns match an empty string at the start of qualifying text. That is enough for a yes/no test. If the tool needs the matched text itself, for example to highlight or extract it, add .* or .*$ at the end.
Common misreadings
- A negated character class is not a negated word. [^cherry]+ means one or more characters that are not c, h, e, r or y. It does not exclude the word "cherry".
- Alternation means OR, not AND. apple|banana matches text containing either term.
- Without word boundaries, apple also matches inside "pineapple". Add \b on both sides when you mean the whole word.
- An unanchored negative lookahead can match text that contains the excluded term. (?!.*cherry) without ^ is retried at every position, and it succeeds at any point after the last "cherry". Anchor it with ^ unless you deliberately want a position-based check.
Excluding a term in the middle of a pattern
Sometimes you want to exclude a term only within one stretch of the match. For example, you might match from BEGIN to the next END without crossing another BEGIN. The tempered greedy token handles this: it checks the negative lookahead before consuming each character.
BEGIN(?:(?!BEGIN|END).)*END
The same idea anchored to a whole line, ^(?:(?!cherry).)*$, matches lines that never contain "cherry". It is equivalent to the simpler ^(?!.cherry).$ but harder to read, so keep the tempered form for mid-pattern cases.
Scope: how far a lookahead checks
By default the dot does not match a newline. In multi-line input, .* inside a lookahead therefore checks only up to the end of the current line. With the multiline flag, ^ anchors at each line, which gives line-by-line filtering. With the dotall flag (often s), the dot also matches newlines, so the condition applies to the whole input. Choose the flags based on whether "contains" means "this line contains" or "this document contains".
Word boundaries and case also vary. Engines define \b and \w differently for non-ASCII letters. In JavaScript they are ASCII-based even with the u flag, while Python 3 treats string patterns as Unicode by default. Case-insensitive matching needs a flag, and inline flag syntax such as (?i) is not supported everywhere.
Engine support
| Engine or context | Lookahead | Practical note |
| PCRE (PHP; grep -P where built with PCRE) | Yes | The patterns above work as written |
| JavaScript | Yes | Lookbehind is also available in current engines |
| Python re | Yes | Lookbehind must be fixed-width |
| Java, .NET | Yes | The patterns above work as written |
| Go regexp, Rust regex (RE2-style) | No | Designed for guaranteed linear-time matching; use multiple checks |
| POSIX ERE (grep -E, awk, many sed builds) | No | Chain commands instead |
Alternatives without lookaround
Separate checks are often clearer than a combined pattern and work in every engine. On the command line, pipe one filter into the next:
grep -w 'apple' file.txt | grep -w 'banana' | grep -vw 'cherry'
In code, combine simple searches with the language's own boolean operators:
import re
ok = (re.search(r'\bapple\b', s)
and re.search(r'\bbanana\b', s)
and not re.search(r'\bcherry\b', s))
For AND without lookahead, you can also list every order explicitly, as in apple.*banana|banana.*apple. This works for two terms, but the number of orderings grows quickly with each added term, so it does not scale.
Copying a pattern from a tester into code
- Set the tester to the same flavor as your target engine. A pattern that passes in a PCRE tester can fail or behave differently in Go or POSIX tools.
- Flags usually do not travel with the pattern text. Settings such as case-insensitive, multiline and dotall must be set again in the destination.
- Escape for the host language. In a Java string literal, \b becomes \b. In Python, use raw strings. In JavaScript, a regex literal and a string passed to the RegExp constructor need different escaping.
- In a shell, wrap patterns in single quotes so the shell does not interpret $, ! or backslashes.
- Watch line endings. With Windows-style CRLF input, a carriage return can sit before $ and cause unexpected misses.
Readability and performance
Each condition you add makes a combined pattern harder to review. Engines with a verbose or extended mode, such as Python's re.VERBOSE or PCRE's (?x), let you split the pattern across lines with comments. JavaScript has no equivalent. On performance, each anchored lookahead rescans the line, which is usually acceptable. The larger risks are unanchored lookaheads on long inputs and nested quantifiers, which can cause heavy backtracking. No measurements were available for this review, so test against realistic input sizes if speed matters.
How to check a pattern before relying on it
- Text that should match, with required terms in both orders.
- Text where the excluded term appears before the required term, and text where it appears after.
- The term embedded in a longer word, such as "pineapple".
- Terms at the very start and very end of the input.
- Multi-line input, checked with and without the multiline and dotall flags.
- Case variants and non-ASCII text if your data includes them.
- An empty string.
Limits of this review
No specific regex testing tool was evaluated, and no performance tests were run. The engine behavior described here reflects general documented behavior, and details can change between versions. Confirm lookaround support, flag syntax and Unicode handling in the documentation for the exact engine and version you use.