Regex for Not: How to Negate Patterns, Exclude Matches and Match Everything Except

Regular expressions have no single NOT operator. See how negated character classes, negative lookarounds and inverted matching work, and when to use each.

People searching for a regex for "not" usually want one of three things. They want to match characters outside a set, to match text that does not contain a word or pattern, or to keep only the lines that fail a pattern. Regular expressions have no general NOT operator that covers all three cases. Each case uses a different mechanism, and each mechanism matches different text. This review explains what each form does, where it breaks, and when it is simpler to leave the negation outside the regex.

Short recommendation

  • To exclude single characters, use a negated character class such as [^0-9]. It is supported almost everywhere and is easy to read.
  • To exclude a word, a substring or a following or preceding pattern, use a negative lookahead (?!...) or a negative lookbehind (?<!...). Check first that your regex engine supports lookarounds.
  • To keep lines that do not match, invert the result outside the regex, for example with grep -v or an if-not test in your code. This is often clearer and more portable than writing a negated pattern.

The main benefit of negation inside the regex is that one pattern does the whole job, which helps when a tool accepts only a single expression. The decisive tradeoff is readability and portability. Lookaround-based negation is harder to read, easier to get subtly wrong, and not available in every engine. When you control the surrounding code or command, a plain positive pattern combined with an inverted test is usually the better choice.

What each form of negation actually matches

Negated character class: [^...]

A caret as the first character inside square brackets inverts the set. [^0-9] matches exactly one character that is not a digit. The class still consumes a character, so it cannot match an empty string, and it can match a newline unless the newline is listed in the set. The caret has a different meaning outside brackets, where it anchors the match to the start of the string or line. That difference causes much of the confusion around regex negation.

[^0-9]+      one or more characters that are not digits
[^,\n]+      a run of text up to the next comma or newline
[^"]*        everything between quotes, used as "[^"]*"

A common mistake is to write [^error] to exclude the word "error". That class excludes the individual letters e, r and o in any order. It does not exclude the word. Character classes work on single characters only, so excluding a word requires a lookaround.

Negative lookahead: (?!...)

A negative lookahead is a zero-width assertion. At the current position it checks that the enclosed pattern does not match next, and it consumes no characters. This is the standard way to write "match X, but not when followed by Y" and "match a line that does not contain Y".

foo(?!bar)              "foo" when it is not followed by "bar"
                        (matches in "foobaz", not in "foobar")

^(?!.*\berror\b).*$     a whole line that does not contain the word "error"
                        (use multiline mode to test each line)

\b(?!test\b)\w+         any word except exactly "test"
                        ("testing" still matches)

Where you place the lookahead matters. ^(?!error) only checks that the line does not start with "error". The .* inside ^(?!.*error) extends the check across the rest of the line. Without the ^ anchor, the engine can try the assertion at a later position where it passes, so the line can still match even though "error" appears in it.

Negative lookbehind: (?<!...)

A negative lookbehind checks that the enclosed pattern does not end immediately before the current position. It is useful for "match a pattern but exclude it when preceded by something".

(?<!\$)\b\d+\b          a number not directly preceded by a dollar sign
(?<!\\)"                a double quote that is not escaped with a backslash

Tempered token: match everything except a sequence

To match a span of text that never contains a given sequence, put a negative lookahead in front of each character the pattern consumes. This form is sometimes called a tempered greedy token. It runs the check at every position instead of once at the start.

^(?:(?!error).)*$       a line in which "error" never appears
START(?:(?!END).)*END   from START to the first END, never crossing another END

Comparison of the main approaches

Approach | Syntax | Excludes | Consumes characters | Portability
Negated character class | [^abc] | Single characters from a set | Yes, one per repetition | Supported in essentially all regex flavors
Negative lookahead | (?!pattern) | A pattern starting at the current position | No | Common in modern flavors; missing from POSIX tools and RE2
Negative lookbehind | (?<!pattern) | A pattern ending at the current position | No | Support and allowed pattern shapes vary by engine
Tempered token | (?:(?!pattern).)* | A sequence anywhere in the span | Yes | Same requirements as lookahead
Inverted match outside regex | grep -v, if not match | Whole lines or strings matching the pattern | Not applicable | Works with any engine

Will a negated pattern still work after copying it elsewhere?

A regex is plain text, so copying it does not change its characters. The risk is that the destination interprets those characters differently. Before you rely on a pattern copied from a tester, an answer or another codebase, check the following points.

  • Engine support: PCRE, Python, Java, .NET and modern JavaScript support lookahead. RE2, the engine behind Go's regexp package, deliberately omits lookarounds. Basic and extended POSIX regex in grep and sed omit them too, although GNU grep -P switches to PCRE syntax.
  • Lookbehind limits: JavaScript added lookbehind in ES2018, so older runtimes reject it. Python's re module requires lookbehind patterns of fixed width, while .NET accepts variable-length lookbehind. Check the documentation for the exact version you run.
  • Escaping: a pattern pasted into a string literal in Java, JSON or a non-raw Python string usually needs every backslash doubled. Shells also need appropriate quoting.
  • Flags: whether ^ and $ match per line, and whether . matches newlines, depend on multiline and dotall flags. A line-based negation that works in a tester can fail on a multi-line string if these flags differ.
  • Testers: an online regex tester is reliable only when it is set to the same flavor and flags as your target. A match in one flavor does not prove the pattern works in another.

Readability matters for anyone who maintains the pattern later. Nested lookarounds are hard to review, and an error in placement silently changes what is excluded. If your engine supports a verbose or extended mode, use it to add inline comments. Otherwise, add a short comment beside the pattern that states, in words, what it should exclude.

When plain code or an inverted match is the better choice

If the goal is to drop the lines or strings that contain something, a simple positive pattern with an inverted test is usually easier to read and works in every flavor.

grep -v 'error' app.log

kept = [line for line in lines if not re.search(r"\berror\b", line)]

Plain code is also the better choice when the exclusion has several conditions, when the rule needs to be explained to non-specialists, or when the target engine lacks lookarounds. Performance can also matter. Patterns that combine lookarounds with broad quantifiers such as .* repeat their checks at many positions, which can be noticeably slow on long inputs in backtracking engines. No benchmark data was supplied for this review, so measure performance with your own data before relying on a complex negated pattern in a hot path.

Gaps in this review

No source material specific to a particular regex tool, tester or engine version was available for this review. The behavior described above reflects widely documented regex semantics, not tests run for this article. It includes no measurements of speed or compatibility. Confirm lookaround support, lookbehind restrictions and flag defaults in the documentation of the exact engine and version you use, and test the pattern there against inputs that should match and inputs that should not.