Lookbehind
Check what came before the current position with (?<=...) and (?<!...). JavaScript allows any length, Python needs a fixed width, PCRE and Perl sit in between.
Lookbehind
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- (?<=X) succeeds if X matches immediately before the current position, and (?<!X) succeeds if it does not. Like lookahead, neither consumes characters.
- (?<=\$)\d+ pulls the digits out of $10 and leaves the dollar sign behind. It is how you say after this, without including this.
- JavaScript allows variable-length lookbehind, such as (?<=\$|USD ) or (?<=a+). Python 3.9 insists on one fixed width, and pcre2grep allows alternatives of different lengths but not a +.
- Perl 5.34 accepts variable length only up to 255 characters, with an experimental warning, and rejects (?<=a+).
- (?<!\d)\d{3}(?!\d) matches a run of exactly three digits: the negative lookbehind and negative lookahead stop the run from continuing in either direction.
Looking at what is already behind you
Lookahead answered “what comes next?” Often the question points the other way. In $10 €20 $30 40, you want the numbers in dollars: 10 and 30. The only thing that tells them apart from 20 and 40 is the character just before each.
A lookbehind is the mirror image of lookahead. (?<=X) succeeds if X matches immediately before the current position. (?<!X) succeeds if it does not. And as with lookahead, nothing is consumed: the engine’s position doesn’t move.
const p = '$10 €20 $30 40';
p.match(/(?<=\$)\d+/g) // [ '10', '30' ]
p.match(/(?<!\$)\b\d+/g) // [ '20', '40' ]
The first is “digits preceded by a dollar sign”. The dollar sign gets checked but never ends up in the result. The second flips it, and the \b is there for the reason from the lookahead lesson: without it, a negative check right before \d+ would let the number start in the middle of 10, after the 1. Because a lookbehind is a test at a position, '$10'.replace(/(?<=\$)/, 'USD ') printed $USD 10: the match is empty, so only the insertion happened.
A neat use is “a run of exactly three digits”, combining both directions:
'1234 567 89 1000'.match(/(?<!\d)\d{3}(?!\d)/g) // [ '567' ]
The lookbehind refuses to start in the middle of a longer run, and the lookahead refuses to stop before one ends.
The portability catch: how long can the lookbehind be?
How does an engine check “what’s before me”? The simple way is to step back by the length of the thing and see if it matches there. That needs a known length. This is why lookbehind has restrictions in older or more cautious engines, and why the rules differ by flavour. I tried the same four patterns in each:
JavaScript Python 3.9 Perl 5.34 pcre2grep
(?<=\$|USD )\d+ ok error ok, experimental ok
(?<=\$|U)\d+ ok ok ok ok
(?<=a+)b ok error error (over 255) error
(?<=x{1,2})y ok error ok, experimental ok
Python 3.9’s error message for the failures is the same each time: look-behind requires fixed-width pattern. Two alternatives are allowed as long as they have the same width (\$|U passed, \$|USD failed). Perl 5.34 warned Variable length lookbehind is experimental for the mixed-width cases and refused (?<=a+)b with Lookbehind longer than 255 not implemented. pcre2grep accepted the different-length alternatives and rejected a+ with length of lookbehind assertion is not limited. pcre2grep accepted x{1,2} too, a bounded range, where the unbounded a+ was the problem.
JavaScript accepted all four, and 'aaab'.match(/(?<=a+)b/g) returned ['b']. The practical rule: if you need the pattern to run in Python or in pcre2grep, keep each lookbehind to a fixed width (or alternatives that have one). If JavaScript is the only target, you are free of that limit. I haven’t tested support in older browsers, and I’d check before relying on it in code that has to run on them.
It really runs backwards in JavaScript
A detail from the ECMAScript design that shows up when a lookbehind contains groups. JavaScript matches the inside of a lookbehind from right to left. The result is surprising the first time:
/(?<=(\d+)(\d+))$/.exec('1053')
// [ '', '1', '053', index: 4 ]
Reading left to right, you’d expect the greedy (\d+) first to take most digits. Group 1 got 1 and group 2 got 053, because the engine matched the second group first, walking leftwards from the end, and let it be greedy. It only matters if you capture inside lookbehinds, which is rare. For ordinary yes-or-no checks, direction makes no difference.
Start of string
A lookbehind at index 0 sees an empty past. /(?<!\w)cat/.exec('cat') matched at index 0, since there is no word character before the c, and /(?<=\w)cat/.exec('cat') returned null. This is the same quiet behaviour as \b at the start of a string, and it’s why (?<!\w) is a common stand-in for “a word starts here”.
About the video
The embedded video is anthonywritescode’s “regex lookahead / lookbehind (intermediate) anthony explains #437”, published 3 June 2022 and 7 minutes 41 seconds long. The description says it shows how lookaheads and lookbehinds validate surrounding text without matching it. It has no chapters, and it uses Python. I couldn’t read a transcript, so I can’t say whether it covers the fixed-width rule, which I’d expect from a Python video but have not confirmed. Because it handles both directions in one sitting, it is useful here as a recap of the previous lesson too. English per its title and description. Koolac’s ten-minute Python video, listed under “deeper”, covers only the positive lookbehind.
What I did not run
GNU grep, newer Python versions (which might relax the fixed-width rule, I don’t know), .NET, Java, and the browser support table for lookbehind in older Safari.
Next
Each lookaround is a small yes-or-no test at a position. Combining lookarounds stacks several of them at one spot, for rules like “must contain a digit and a capital”.
Check yourself
How do you extract only the numbers that follow a dollar sign in $10 €20 $30 40?
/(?<=\$)\d+/g returns ['10', '30']. The lookbehind requires a dollar sign right before the digits and leaves it out of the match.
Why does re.compile(r'(?<=\$|USD )\d+') fail in Python 3.9?
Python needs a lookbehind to have one fixed width, and the two alternatives are one and four characters long. The error is 'look-behind requires fixed-width pattern'. It works in JavaScript, and in pcre2grep.
How would you match a number with exactly three digits and nothing around it, using only lookarounds and \d?
(?<!\d)\d{3}(?!\d). On 1234 567 89 1000 it matches only 567, because every other digit run is the wrong length.
What is the practical difference between /(?<!\w)cat/ and /(?<=\w)cat/ on the input cat?
The negative one matches at index 0, since nothing precedes it, and the positive one fails because there is no word character before. A lookbehind at the start of the string sees an empty past.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.