Negative Lookbehind Regex: Match Text Only When It Isn't Preceded by Something

Learn how a negative lookbehind regex (?<!...) works, how to build and test one step by step, which engines support it, and what to do when they don't.

A negative lookbehind lets a regular expression match something only when it is not immediately preceded by a certain pattern. Use it to find numbers that aren't prices, quotes that aren't escaped, or words that don't carry a particular prefix, without touching the surrounding text.

What a negative lookbehind does

A negative lookbehind is an assertion, which means it checks a condition rather than matching characters. At the current position in the text, the engine looks to the left and asks whether the lookbehind pattern ends right there. If it does, the match attempt fails at that position. If it does not, matching continues. The check is zero-width: it consumes no characters, so the text it inspects is never part of the match.

Its input is any plain text you search or run a replacement on. It changes nothing by itself. It only narrows which positions are allowed to match. In a search-and-replace, only the matched target is replaced, and the preceding text that the lookbehind checked stays exactly as it was.

(?<!PATTERN)TARGET

Read as: match TARGET, but only where PATTERN does not end immediately before it.

The related assertions are the positive lookbehind (?<=...), which requires the preceding pattern, and the negative lookahead (?!...), which checks the text to the right of the position instead of the left.

A first example

Pattern:  (?<!un)happy
Text:     happy unhappy
Expected: matches the first "happy" only

In this illustrative example, the second "happy" is skipped because the two characters before it are "un". The lookbehind does not stop other prefixes, so "veryhappy" would still match.

Why not use a negated character class instead?

A common first attempt is something like [^$]\d+, meaning "a character that isn't a dollar sign, then digits." This has two problems. First, the class consumes a character, so that character becomes part of the match and would be removed or changed by a replacement. Second, it needs a character to be there at all, so it cannot match at the very start of the text. A lookbehind avoids both problems, because it consumes nothing and treats the start of the text as "not preceded by the pattern."

Text:                7 apples, $5 pears, 12 plums

[^$]\d+             expected matches: " 12" (includes the space; misses 7)
(?<![$\d])\d+        expected matches: "7", "12"

Avoiding partial matches inside a longer token

The lookbehind checks only the position directly before where the match starts. With the pattern (?<!$)\d+ and the text $40, the engine rejects a match starting at 4, but it can still start at 0, because 0 is preceded by 4 rather than by $. The result would be an unwanted match of "0".

The fix is to also forbid a digit right before the match, so it can never begin mid-number. That is why the example above uses (?<![$\d])\d+. Inside a character class, $ is a literal dollar sign in mainstream regex flavors. Outside a class, it must be escaped as $ because it otherwise means "end of line or string."

How to build and verify a negative lookbehind step by step

  • 1. Write down the target, which is the text you want to match, and separately the preceding text that should block it.
  • 2. Pick the regex flavor that matches where the pattern will run (JavaScript, Python, PCRE, Java, .NET and so on). Support and length rules differ, as shown below.
  • 3. Write the target pattern alone and confirm it matches every candidate.
  • 4. Add (?<!...) directly in front of the target, containing the blocking pattern. Escape special characters such as $, ., (, ) and backslash.
  • 5. Paste sample text that includes both cases: targets that should match and targets that should be skipped.
  • 6. Add edge cases, such as a target at the very start of the text, at the start of a line, right after the blocking text, and inside a longer word or number.
  • 7. Check the highlighted matches. If a match starts in the middle of a token, widen the lookbehind (for example, add \d or \w to a character class).
  • 8. If you are replacing text, preview the replacement and confirm that the preceding characters remain unchanged and only the target is replaced.

Examples in JavaScript and Python

The snippets below are illustrative. The commented results show what the pattern is expected to produce based on standard lookbehind behavior. They are not captured output from a test run.

// JavaScript (lookbehind requires an ES2018-or-later engine)
const text = "7 apples, $5 pears, 12 plums";
const matches = text.match(/(?<![$\d])\d+/g);
// Expected: ["7", "12"]
# Python
import re

text = "7 apples, $5 pears, 12 plums"
print(re.findall(r"(?<![$\d])\d+", text))
# Expected: ['7', '12']

print(re.sub(r"(?<![$\d])\d+", "#", text))
# Expected: # apples, $5 pears, # plums

The replacement example shows the key property: the $5 is left alone, and the spaces before 7 and 12 are not consumed or altered.

Engine support and length limits

Engine | Negative lookbehind | What the lookbehind may contain
JavaScript (ES2018 and later) | Supported | Patterns of any length
Python re | Supported | Fixed-width patterns only
Python regex (third-party module) | Supported | Variable-length patterns
PCRE / PCRE2 (PHP, grep -P) | Supported | Fixed length per top-level alternative; recent PCRE2 releases relax this, so check your version
Java | Supported | Bounded length; no unbounded * or +
.NET | Supported | Patterns of any length
Go regexp (RE2) | Not supported | Not applicable
Rust regex crate | Not supported | Not applicable
POSIX basic/extended (grep, grep -E, sed) | Not supported | Not applicable

This table summarizes widely documented general behavior. It was not checked against a specific tool or version for this article. Confirm support in your engine's documentation, or select the matching flavor in your regex tester, before relying on it.

When the lookbehind needs a different length or isn't supported

In Python's re module, (?<!Mr|Mrs). raises an error because the two alternatives have different widths. Stacking separate fixed-width lookbehinds gives the same logic, since each one must pass:

Pattern:  (?<!Mr)(?<!Mrs)\.
Text:     Mr. Smith met Mrs. Jones.
Expected: matches only the final period
  • If lookbehind is unavailable (for example in Go or POSIX tools), match the preceding context explicitly and capture the target: (?:^|[^$\d])(\d+). Then use capture group 1. In a replacement, put the captured context back so it isn't lost.
  • Alternatively, match all candidates with a simple pattern and filter them in code by inspecting the characters before each match position.
  • For command-line work, grep -P provides PCRE lookbehind where your grep build includes PCRE support.

Common pitfalls

  • Placement: the lookbehind tests the text before its own position. \d+(?<!$) checks the character just before the end of the match, which is always a digit, so it never blocks anything. Put the lookbehind before the target.
  • Escaping: a backslash inside the lookbehind must itself be escaped. (?<!\)" means "a quote not preceded by a backslash."
  • Case: (?<!un) does not block "Unhappy" unless you enable case-insensitive matching.
  • Line boundaries: a lookbehind can see the previous line's last character, such as a newline, so test targets at the start of lines.
  • Unicode: in some engines \d and \w match non-ASCII digits and letters by default (Python 3 string patterns do, for example). Use explicit ranges like [0-9] if you only mean ASCII.
  • Invisible characters: a non-breaking space or zero-width character before the target counts as a preceding character. If matches seem wrong, make whitespace visible in your tester.

Escaped-quote patterns illustrate a limit of lookbehind. With (?<!\)" on the text say "hi" and "bye", the expected matches are only the two quotes around bye. However, a quote after an escaped backslash, written \", is a real closing quote, and the simple lookbehind would wrongly skip it. Counting backslashes reliably needs a more complex pattern or a proper parser.