Regex Contains and Not Contains: Patterns for Required and Forbidden Text
How to write regex that requires some text and forbids other text, how lookaheads work, where they fail, and when a plain string check is the better choice.
Checking that text contains something is the easy half of regular expressions. Requiring that text does not contain something, or combining both conditions, is where patterns become awkward and where engines start to disagree. This review covers patterns for required text, forbidden text and both together. It explains what those patterns do and do not change, how they hold up when copied between tools, and when a plain string check or an inverted match in code is the better option. No tool-specific test results or benchmarks were available for this article. The behavior described here is documented engine behavior, so confirm it in the engine you actually deploy to.
Short answer: when a single pattern is the right tool
Use one regex with lookahead assertions when the condition has to live in a single pattern. Typical cases are form validation rules, configuration files, log filters and search fields that accept only a regex. The main benefit is a self-contained expression that one setting can carry. The decisive tradeoff is portability and correctness: some widely used engines do not support lookarounds at all, and multiline input is easy to get wrong. If you control the surrounding code, a plain substring check combined with a boolean NOT is usually clearer, works in every language and is harder to break.
Contains: the straightforward case
A literal pattern already means 'contains' in most search and test functions, because the engine looks for a match anywhere in the input. The usual refinement is a word boundary, so that searching for error does not also match terror or errors. Case-insensitive matching is turned on with a flag. PCRE, Python, Java and .NET accept a leading inline (?i). JavaScript expects the i flag on the regex instead.
error matches "error", "terror", "errors"
\berror\b matches the whole word "error" only
(?i)\berror\b same, case-insensitive (PCRE, Python, Java, .NET)
/\berror\b/i same, case-insensitive (JavaScript)
Does not contain: negative lookahead
Regex has no direct NOT operator for a whole substring. The standard workaround is a negative lookahead anchored at the start of the input.
^(?!.*\berror\b).*$
At the start position, the lookahead (?!.\berror\b) checks whether the word error appears anywhere ahead. If it does, the assertion fails and nothing matches. A lookahead is zero-width: it inspects text without consuming it. The trailing .$ then consumes the line so the match returns the text itself. If you only need a yes-or-no answer, ^(?!.*\berror\b) is enough.
A second form, often called a tempered greedy token, checks every character position as it advances: ^(?:(?!\berror\b).)*$. On a single line it gives the same result as the anchored lookahead. Some readers find it clearer when the forbidden text must be absent from one specific stretch of a larger pattern rather than from the whole input.
If the forbidden item is a single character, no lookaround is needed. A negated character class such as ^[^@]*$ matches only input with no @ sign. This form works in POSIX tools and other engines that lack lookahead.
Contains one thing but not another
Positive and negative lookaheads can be chained at the start of the pattern. Each assertion scans ahead independently, so the required and forbidden words can appear in any order. To require more words, add more (?=...) groups. To forbid more words, add more (?!...) groups.
^(?=.*\bapple\b)(?!.*\bbanana\b).*$
| Input | Matches? | Reason |
| apple pie | Yes | contains apple, no banana |
| apple and banana | No | banana is present |
| pineapple tart | No | no word boundary before apple inside pineapple |
| banana bread | No | apple is missing |
| Apple pie | No, unless case-insensitive | Apple differs from apple by case |
The table above was derived by reasoning through the documented behavior of the pattern, not by running it in a named tool. Run the same rows through your target engine before you rely on the pattern.
Other things people mean by 'match if not'
- Not immediately followed by: foo(?!bar) matches foo unless bar comes right after it. It does not forbid bar elsewhere in the line.
- Not immediately preceded by: (?<!un)happy matches happy unless un comes right before it. Lookbehind support varies. Python requires fixed-width lookbehind, and older browser JavaScript engines, notably older Safari versions, lack lookbehind entirely.
- Lines that do not match: in command-line filtering, grep -v error prints every line without error. No lookaround is needed.
- Conditional patterns: PCRE, Python and .NET support (?(1)yes|no), which picks a branch depending on whether an earlier group matched. JavaScript does not support this syntax.
- Not matching at all: in code, testing the pattern and negating the boolean result is often the simplest 'does not match' check.
What these patterns actually change
Matching changes nothing in the text. A test or search reports whether and where a pattern matches, and lookarounds are assertions that consume no characters. Only a replace operation alters stored text. That matters with not-contains patterns: because ^(?!...).*$ matches the entire line, using it in a replace rewrites whole lines, not just a fragment. Nothing here involves reversed characters, mirrored glyphs or substituted Unicode styling; the input stays exactly as it was unless you explicitly replace it.
Unicode does affect what counts as a word. In JavaScript, \w and \b are ASCII-based, so é is not treated as a word character, and \bcaf\b will match the caf inside café. Python 3 patterns on str input treat accented letters as word characters by default, so the same pattern does not match there. If your text includes non-ASCII words, test boundaries and case-insensitive matching with representative samples.
Multiline input: the most common mistake
By default, the dot does not match line breaks. With no flags, ^ anchors to the start of the whole input, and the .* inside the lookahead stops at the first newline. As a result, ^(?!.*error) checks only the first line, and a document with error on line three still passes. Decide which behavior you want. To forbid the word anywhere in the input, enable dot-all mode or use a character class that includes newlines. To evaluate each line separately, enable multiline mode so ^ and $ apply per line. Windows line endings can leave a stray carriage return before $, so check that too.
Whole input, PCRE/Java/Python inline flag: (?s)^(?!.*\berror\b)
Whole input, JavaScript: /^(?![\s\S]*\berror\b)/
Each line separately, JavaScript: /^(?!.*\berror\b).*$/gm
Engine support and portability
- Lookahead supported: PCRE (including grep -P and PHP), Python re, Java, .NET and JavaScript.
- No lookaround: RE2, Go's regexp package and Rust's regex crate. Use two separate matches in code, one required and one negated.
- No lookaround: POSIX basic and extended regex as used by grep, grep -E, sed and awk. Chain filters instead, for example grep apple | grep -v banana.
- Databases and SaaS filter fields: support differs by product and version. Check the documentation rather than assuming PCRE behavior.
Copying patterns between testers, code and configs
Online regex testers usually let you choose a flavor, and a pattern that passes in a PCRE tester can fail or behave differently in JavaScript, and won't compile in Go. Set the tester to your target flavor, then repeat the check in the destination itself. One successful run in a tester does not establish behavior elsewhere. This article does not evaluate or compare specific testers, and it makes no claims about how any tester handles the text you paste into it.
Escaping changes when a pattern moves into a string literal. Languages without raw strings, and formats such as JSON, need each backslash doubled. A pattern copied from a tester into one of these without that adjustment silently loses its word boundaries.
Python raw string: r"^(?!.*\berror\b).*$"
Java string: "^(?!.*\\berror\\b).*$"
JSON string value: "^(?!.*\\berror\\b).*$"
Text copied from web pages, chat apps or word processors can carry characters that look identical to the intended ones: curly quotes, non-breaking spaces and zero-width characters. These cause matches to fail without an obvious error. If a pattern that should match does not, retype the literal parts or inspect the code points.
Readability and maintenance
Stacked lookaheads are hard to read and easy to edit incorrectly. Extended or verbose mode lets you split a pattern across lines and add comments. It is available as the x flag in PCRE, re.VERBOSE in Python and the COMMENTS flag in Java. JavaScript's standard flags do not include an equivalent, so a plain-language comment next to the pattern is the practical substitute there.
pattern = re.compile(r"""
^
(?=.*\bapple\b) # must contain the word apple
(?!.*\bbanana\b) # must not contain the word banana
.*$
""", re.VERBOSE)
When plain code beats a clever pattern
- You control the code: "apple" in text and not "banana" in text, or the equivalent includes checks, is clearer and portable.
- The target engine lacks lookaround, such as Go, RE2-based services or POSIX tools.
- The rule will grow: several required and forbidden terms are easier to keep as a list in code than as a long chain of assertions.
- Other people must review or change the rule, and a readable condition is worth more than a one-line pattern.
Gaps and open questions
No benchmark data, tool evaluations or engine-specific test runs were available for this review. Treat the examples as documented behavior to verify, not as observed results. On performance, an anchored lookahead with .* scans the line once per match attempt, so test it on the largest inputs you expect. The well-known risk of excessive backtracking comes mainly from nested or overlapping quantifiers, which these basic patterns avoid. Version-specific support for lookbehind and inline flags also changes over time, so check the current documentation for your runtime.