Negate a regex
How to negate a regular expression: negated character classes, negative lookahead and lookbehind, inverted matching with grep -v, engine support, and how to check the result.
Regular expressions have no single "not" operator. The right approach depends on what you want to exclude: certain characters, a word or substring, text at a specific position, or every line that matches a pattern. This guide covers each case with examples and explains how to check that the pattern excludes only what you intend.
What negating a regex does to your text
Negation is a matching operation. It does not change your text. The input is a string or a set of lines. The output is either the matches that remain after the unwanted cases are ruled out, or a filtered set of lines that do not match. Your text only changes if you use the negated pattern in a replace operation. In that case, a pattern that is too broad can rewrite content you meant to keep, so test the match before you replace anything.
Choose the right kind of negation
| Goal | Technique | Example pattern |
| Match any character except certain ones | Negated character class | [^0-9] |
| Match lines that do not contain a word | Anchored negative lookahead | ^(?!.error).$ |
| Match text not followed by something | Negative lookahead | foo(?!bar) |
| Match text not preceded by something | Negative lookbehind | (?<!.min).js$ |
| Match any word except one | Lookahead at a word boundary | \b(?!cat\b)\w+\b |
| Match a span that never contains a sequence | Tempered greedy token | START(?:(?!END).)* |
| Keep everything the pattern does not match | Invert outside the regex | grep -v 'error' |
Exclude characters with a negated character class
A caret placed first inside square brackets negates the class. The class then matches any single character that is not listed. Outside brackets, the caret means "start of line or string", so its meaning depends on where it appears.
[^0-9]+ one or more characters that are not ASCII digits
[^,]+ a run of characters up to the next comma
[^\s] any non-whitespace character (same as \S)
[^"]* everything up to the next double quote
Watch for two things. First, a negated class excludes single characters, not words: [^cat] means "not c, a or t", not "not the word cat". Second, a negated class usually matches newlines too. For example, [^,]+ can run across line breaks in a multi-line string. If that matters, add the newline to the class, as in [^,\n]+.
Match lines that do not contain a word
A negative lookahead, written (?!...), is a zero-width check. It does not consume any characters. It only succeeds if the text inside it cannot match at the current position. If you anchor it at the start of the line and put .* inside, it checks the whole line.
^(?!.*error).*$
Illustrative input (three lines):
info: started
error: disk full
warning: Error rate high
Expected result, worked out from the pattern logic rather than from tool output: with case-sensitive matching, lines 1 and 3 match, because "Error" with a capital E is not "error". With the case-insensitive flag, only line 1 matches. Use \berror\b if "errors" or "terror" should not count as matches. When you test the pattern against a whole block of text rather than line by line, turn on the multiline flag so that ^ and $ match at each line break.
Exclude text at a specific position
Lookarounds let you reject a match based on what comes before or after it, without including that context in the match.
foo(?!bar) "foo" not followed by "bar"
^(?!test_)\w+ identifiers that do not start with test_
(?<!\$)\b\d+\b numbers not preceded by a dollar sign
(?<!\.min)\.js$ .js file names that are not .min.js
A negative lookbehind, written (?<!...), checks the text just before the current position. Some engines only accept lookbehinds of a fixed width; Python's built-in re module is one of them. If your engine rejects a lookbehind, rewrite it with a fixed-length alternative, or move the check into code.
Match any word except one
\b(?!cat\b)\w+\b
At each word boundary, the lookahead rejects the position if the next word is exactly "cat". The \b inside the lookahead is important. Without it, words that merely start with "cat", such as "category", would also be skipped. To exclude several words, list them as alternatives: \b(?!(?:cat|dog)\b)\w+\b.
Match a span that never contains a sequence
A tempered greedy token checks the lookahead before consuming each character. As a result, the match never runs through the forbidden sequence. This is useful for matching blocks between markers when a negated character class can't express the boundary, because a class only excludes single characters, not sequences such as END.
START(?:(?!END).)*
By default, the dot does not match newlines. Enable the dotall (single-line) flag if the span can cross line breaks.
Invert the match outside the regex
Often the clearest solution is to keep the regex positive and invert the result in the tool or code that runs it. This avoids lookarounds entirely and works in engines that do not support them.
grep -v 'error' app.log lines without "error"
grep -vi 'error' app.log same, ignoring case
grep -vE 'error|warn' app.log lines with neither word
import re
kept = [line for line in lines if not re.search(r"\berror\b", line)]
Check that your engine supports the syntax
- Negated character classes such as [^...] work in essentially every regex flavor, including POSIX grep and sed.
- Lookahead and lookbehind are not part of POSIX basic or extended regular expressions, so plain grep and grep -E reject them. GNU grep accepts them with -P (Perl-compatible mode) when built with that support.
- PCRE-based tools, JavaScript, Python, Java and .NET support negative lookahead. Lookbehind rules vary between them.
- RE2 and Go's regexp package deliberately do not support lookarounds. In those environments, invert the result in code instead.
- An online regex tester only reflects the flavor it is set to. Select the flavor that matches where the pattern will actually run.
Verify the result step by step
- Write a small sample that includes lines that should match, lines that should be excluded, and edge cases such as capitalization, plural forms, the word at the very start or end of a line, and empty lines.
- Run the pattern in a tester set to your target flavor and confirm which lines or spans are highlighted.
- Check the flags: case-insensitive, multiline for per-line anchors, and dotall if spans cross line breaks.
- Count the results against what you expected. With grep, compare grep -c with grep -vc. The two counts should add up to the total number of lines.
- Before using the pattern in a replace operation, preview the replacements or run them on a copy of the text, so that meaningful content is not changed unintentionally.
Limits of this guide
No specific tool, version or benchmark was provided as evidence for this article. The patterns above follow widely documented regex behavior. The expected results are reasoned from that behavior and were not produced by running a tool. Flavor details, especially lookbehind rules and how Unicode affects \w and \b, differ between engines and versions, so confirm them in the documentation for the engine you use.