Lookahead
Check what comes next without consuming it: (?=...) requires, (?!...) forbids. Learn zero-width matching, the backtracking trap and which tools support it.
Lookahead
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 right here, and (?!X) succeeds if it does not. Neither one uses up any characters, so the match continues from the same spot.
- The text inside a lookahead is checked but never becomes part of the result. \d+(?= USD) on 10 USD returns 10, not 10 USD.
- A lookahead matches a position, not text. 'abc'.replace(/(?=b)/, '|') gives a|bc, and the match itself is the empty string.
- A negative lookahead right after a quantifier is easy to fool, because the quantifier backs off. \w+(?!,) on abc, still returns ab. Anchor the word with \b first.
- JavaScript, Python, Perl and PCRE have lookahead. POSIX grep -E and sed -E do not, and BSD grep has no -P. Use pcre2grep or Perl on the command line.
Needing a condition without a match
You want the dollar amounts from 10 USD 20 EUR 30 USD, but only the USD ones, and only the number. A plain \d+ USD finds 10 USD and 30 USD, and now the currency code is part of what you matched. If you are replacing or extracting, the extra text is in the way. What you want to say is: “digits, but only if USD comes after them, and don’t include the USD in the answer.”
That is a lookahead. It peeks forward from the current position, answers yes or no, and doesn’t move the engine’s position forward. Think of a bouncer who checks the ID of whoever stands behind you in the queue. He isn’t letting that person in. He only decides whether you may pass.
The two forms
(?=X)is the positive lookahead: succeed only ifXmatches starting here.(?!X)is the negative lookahead: succeed only ifXdoes not match starting here.
const s = 'foobar foobaz';
/foo(?=bar)/.exec(s) // 'foo' at index 0
/foo(?!bar)/.exec(s) // 'foo' at index 7
The first finds the foo that is followed by bar. The second finds the other one. In both cases only foo ends up in the result.
For the amounts:
const t = '10 USD 20 EUR 30 USD';
t.match(/\d+(?= USD)/g) // [ '10', '30' ]
t.match(/\d+ USD/g) // [ '10 USD', '30 USD' ]
“Does not consume” is literal
An ordinary part of a pattern consumes characters. Once matched, they’re behind the engine, and the next part starts after them. A lookahead consumes nothing. After it succeeds, the engine is exactly where it was. I proved it by following a lookahead with the same text it checked:
'foobar'.match(/foo(?=bar)/g) // [ 'foo' ]
'foobar'.match(/foo(?=bar)bar/g) // [ 'foobar' ]
'foobar'.replace(/foo(?=bar)/, 'X') // 'Xbar'
In the second line, bar is matched twice in a row: once peeked at by the lookahead and once for real. In the third line, the replacement swapped only foo, and bar stayed in place.
A lookahead is really a test about a position. 'abc'.replace(/(?=b)/, '|') returned a|bc. The match was the empty string at index 1. [...'abc'.matchAll(/(?=b)/g)] gave one match, ['', 1]. This is how patterns insert text at a spot, without any text being matched there.
A lookahead can sit in the middle of a pattern, not just at the end, and it can hold a variable-length body: /x(?=\d+y)/ matched the x in x12y. And it lets you pile conditions at the same spot: /^(?=.*\d)[a-z0-9]+$/ demanded a digit somewhere and then consumed the whole string with the normal part. It returned true for abc1 and false for abcd. The next lessons build on that.
The trap: quantifiers back off
A negative lookahead after a quantifier looks like it should mean “a word not followed by a comma”:
'abc, def'.match(/\w+(?!,)/g) // [ 'ab', 'def' ]
'abc, def'.match(/\b\w+\b(?!,)/g) // [ 'def' ]
The first pattern returned ab. What happened: \w+ greedily took abc, the lookahead saw a comma and failed, so the engine did what backtracking engines do. It gave back one character and tried ab, where the next character is c, not a comma. The lookahead passed. The fix is to stop the word from being shortened: \b after \w+ forces the match to end at a word edge, so ab is no longer an option.
The same thing hit Python. re.findall(r'\d+(?! USD)', t) on the amounts string returned ['1', '20', '3']. 10 became 1 and 30 became 3. Whenever a negative lookahead follows + or *, ask what the quantifier will do when it fails.
Where it works
Python agreed with JavaScript on \d+(?= USD) (it returned ['10', '30']), and pcre2grep -o printed 10 and 30, as did a Perl one-liner (on a shorter input, 10). The shell tools are where it fails:
$ echo '10 USD' | /usr/bin/grep -oE '[0-9]+(?= USD)'
grep: repetition-operator operand invalid
$ echo '10 USD' | /usr/bin/grep -oP '[0-9]+(?= USD)'
grep: invalid option -- P
$ echo '10 USD' | /usr/bin/sed -E 's/[0-9]+(?= USD)/N/'
sed: 1: "s/[0-9]+(?= USD)/N/ ...": RE error: repetition-operator operand invalid
POSIX extended syntax has no lookahead, and BSD grep has no -P. Use pcre2grep -o or Perl. The grep lesson covers what the macOS tools do and don’t have.
About the video
The embedded video is Height Above Sea Level’s “Positive & Negative Lookaheads - RegEx Beginner Tutorial”, published 17 July 2024 and 6 minutes 20 seconds long. Its chapters are an introduction, positive lookahead, negative lookahead, a demo of each in Visual Studio, a recap and “what’s next”. The description says lookaheads work in C#, JavaScript, Java and Python, and that it shows both forms. That matches this lesson’s scope well. I couldn’t read a transcript, so I can’t say whether it mentions the backtracking trap or the missing support in POSIX tools. English per its title and description. The freeCodeCamp-curriculum video under “deeper” is a JavaScript-only alternative.
What I did not run
GNU grep with -P, ripgrep’s -P option, and the video’s Visual Studio demos.
Next
Lookahead checks forward. The mirror image is lookbehind, which checks what came before, and has stricter rules in some flavours.
Check yourself
What does /foo(?=bar)/ return on the string foobar, and what does a following bar match?
It returns foo, and the lookahead leaves bar unconsumed. So /foo(?=bar)bar/ matches the whole foobar, because after the lookahead succeeds the engine is still sitting right after foo.
Given 10 USD 20 EUR 30 USD, how do you extract only the amounts in USD, without the currency code?
/\d+(?= USD)/g. The lookahead requires the text USD to follow but does not include it in the match, so the result is ['10', '30'].
Why does /\d+(?! USD)/g return ['1', '20', '3'] on that same string instead of just ['20']?
For 10 the engine matches 10, sees USD follows and fails the lookahead, then backs off and tries 1, which is followed by 0, not USD, so it passes. A quantifier gives characters back. Add \b around the digits, as in /\b\d+\b(?! USD)/g, so the number cannot be cut short. That returns ['20'].
You have grep -E '[0-9]+(?= USD)' and it errors. What are your options?
POSIX extended syntax has no lookahead. On macOS, grep -E reported 'repetition-operator operand invalid' and BSD grep has no -P. Use pcre2grep -o or a Perl one-liner, or restructure the pattern to capture the number and print the group.
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.