Checking Lookbehind Conditions in Regular Expressions
How regex lookbehind works, what it matches and what it leaves untouched, where engines differ on support and length limits, and when a capture group is the better choice.
A lookbehind is a regex condition that checks what comes immediately before the current position, without including that text in the match. This review explains what a lookbehind does and does not change, where it works well, where engine differences make it fragile, and when a simpler pattern is the better choice. The behavior described here comes from documented engine rules. No tool-specific test results or benchmarks were supplied for this article, so verify anything version-sensitive against the engine you actually run.
Is a lookbehind the right tool for your pattern?
Use a lookbehind when you need to match text only if a certain context comes before it, and you want the match itself to contain only the target. Examples include a number preceded by a currency sign, a word not preceded by a minus sign, or a value after a fixed label. The main benefit is a clean match result. The full match is the part you care about, which matters most in find-and-replace operations and in functions that return only whole matches.
The decisive tradeoff is portability. Lookbehind support and its length rules vary more between regex engines than almost any other common feature. A pattern that works in one tester or language can be rejected outright in another, or be unavailable entirely.
A plain capture group is preferable when your code can read group contents, when the pattern must run on several engines, or when the preceding context has variable length and your engine only allows fixed-width lookbehind. For example, writing $(\d+) and reading group 1 gives the same practical result as (?<=$)\d+ and works almost everywhere.
What a lookbehind actually changes
A lookbehind changes nothing in the text. It is a zero-width assertion: it tests a condition at a position and then either lets matching continue or forces the engine to try elsewhere. It consumes no characters, so the checked context is not part of the match and is not replaced in a substitution.
- Positive lookbehind, written (?<=...): succeeds when the enclosed pattern matches text ending exactly at the current position.
- Negative lookbehind, written (?<!...): succeeds when the enclosed pattern does not match there.
- At the very start of a string nothing precedes the position, so any positive lookbehind fails and any negative lookbehind succeeds.
- Lookbehinds can be combined with lookaheads and with each other, since none of them move the match position.
The word "reverse" causes some confusion. Some engines, including .NET, evaluate a lookbehind by matching its contents right to left from the current position. That is an internal technique; your input is never reversed. There is also an older workaround for engines without lookbehind: reverse the string, use a lookahead, then reverse the results. That workaround does change stored text, and it breaks on any character made of more than one code point, as explained below.
Worked examples
The examples below use Python's built-in re module and JavaScript. The outputs follow from the documented semantics of each pattern.
import re
text = "Total: $42, tax $3, qty 7"
# Positive lookbehind: digits preceded by a dollar sign
re.findall(r"(?<=\$)\d+", text) # ['42', '3']
# Negative lookbehind: whole numbers not preceded by a dollar sign
re.findall(r"(?<!\$)\b\d+\b", text) # ['7']
# Portable alternative with a capture group
re.findall(r"\$(\d+)", text) # ['42', '3']
In the negative example, the word boundary \b matters. Without it, (?<!$)\d+ would also match the "2" in "$42", because the position before "2" is preceded by "4", not by a dollar sign. This is the most common logic error with negative lookbehind. The assertion checks only one position, so the rest of the pattern must stop the match from starting partway through the excluded token.
const text = "Total: $42, tax $3, qty 7";
text.match(/(?<=\$)\d+/g); // ["42", "3"]
Engine support and length limits
Engines differ in whether they support lookbehind at all and in how long the enclosed pattern may be. The summary below reflects documented behavior as generally understood. Rules have changed across versions, so check the documentation for the exact version you use.
| Engine | Lookbehind support | Length rule inside the lookbehind |
| Python re | Yes | Fixed width only; otherwise compile fails with "look-behind requires fixed-width pattern" |
| Python third-party regex module | Yes | Variable length allowed |
| JavaScript (ES2018 and later) | Yes, in engines that implement ES2018 | Variable length allowed; older browsers may lack support |
| .NET | Yes | Variable length allowed |
| Java | Yes | Must have a bounded maximum length; unbounded quantifiers such as * or + are not accepted |
| PCRE / PCRE2 | Yes | Each top-level alternative must be fixed width; recent PCRE2 versions relax this with limited variable length |
| Perl | Yes | Fixed width historically; newer versions offer experimental limited variable length |
| Go (RE2) and Rust regex crate | No | Lookaround is not supported by design |
When fixed width is required, (?<=$\s*)\d+ will fail to compile because \s* has no fixed length. Options include splitting the context into fixed-width alternatives where the engine allows that, using a capture group, or, in PCRE and Perl, using \K. With \K, the pattern $\s*\K\d+ matches the whole sequence but reports only the part after \K as the match.
Characters, code points and fixed width
"Fixed width" is measured in the engine's own units, which are not necessarily what a reader sees as one character. Python counts code points. JavaScript counts UTF-16 code units unless the u or v flag is used. In either case, one visible character can span several units.
- An accented letter may be stored as one precomposed code point or as a base letter plus a combining mark. A lookbehind written with one form will not match text stored in the other unless you normalize both first.
- Many emoji, including flags, skin-tone variants and sequences joined with zero-width joiners, consist of several code points. A lookbehind containing such an emoji has a width equal to all of them, and a dot inside the lookbehind matches only one unit, not the whole emoji.
- In JavaScript without the u flag, a character outside the Basic Multilingual Plane counts as two units, so a dot matches only half of it.
These same issues are why the reverse-the-string workaround is unreliable. Reversing by code point detaches combining marks from their base letters and scrambles multi-code-point emoji. If you must reverse, reverse by grapheme cluster, and treat a native lookbehind as the safer option wherever it is available.
Will the pattern still work after copying or sharing it?
Copying a regex between tools is where lookbehind patterns most often break. The pattern text survives the copy; the problem is that the destination interprets it differently. Check these points whenever you move a pattern:
- Flavor: an online tester set to one engine proves nothing about another. Select the flavor that matches your runtime before relying on a result.
- Support: some environments reject the (?<= and (?<! syntax entirely, including RE2-based tools and basic or extended POSIX modes of command-line utilities. Some tools enable lookbehind only in a Perl-compatible mode.
- Length rules: a variable-length lookbehind that works in JavaScript or .NET can fail to compile in Python re, Java or PCRE.
- Escaping: inside string literals, backslashes may need doubling, as in Java, or a raw string, as in Python. A pattern pasted from a tester into source code without adjusting escapes may compile but mean something different.
- Runtime versions: in browser code, confirm that your supported browsers implement ES2018 lookbehind before shipping a pattern that depends on it.
When a pattern has to work in more than one environment, the portable equivalent is a capture group, or matching the context and trimming it in code afterward. Keep that version alongside the lookbehind version, or use it instead, whenever you cannot confirm support at the destination.
Readability and maintenance
Lookbehinds make a pattern harder to read, especially negative ones or several stacked at one position. In code that others will maintain, a short comment stating the intended condition helps, as does a verbose or extended mode where the engine supports it. A test case covering the start-of-string position and an excluded token next to an allowed one also helps, because those are the cases where lookbehind logic usually goes wrong.
Gaps in this review
No engine-specific test runs, performance measurements or version-by-version support data were supplied for this article. The support table summarizes documented rules and should be treated as a starting point, not a compatibility guarantee. Performance of variable-length lookbehind on large inputs, and the exact version in which a given engine relaxed its length rules, should be checked in that engine's documentation or confirmed with a scoped test in your own environment.