Regex & Text
Regex Lookahead and Lookbehind Explained
A lookaround is a zero-width assertion: it checks context before or after a position without adding that context to the consumed match.
Published
What a lookaround is
The assertion must succeed or fail at the current position, but its own text is not consumed into the match.
Positive lookahead (?=...)
This matches digits only when USD follows.
\d+(?= USD)Negative lookahead (?!...)
This matches foo only when bar does not immediately follow.
foo(?!bar)Positive lookbehind (?<=...)
This matches digits preceded by a dollar sign in JavaScript runtimes with lookbehind support.
(?<=\$)\d+Negative lookbehind (?<!...)
This excludes a number when the tested preceding context is a dollar sign.
(?<!\$)\b\d+Lookaround vs capturing groups
A lookaround checks context without consuming it. A capturing group records text that participates in the match.
Common mistakes
- Expecting assertion text inside the match.
- Assuming every engine has identical lookbehind support.
- Using a lookaround when a simpler boundary would be clearer.
- Building an assertion whose performance is difficult to reason about.
Try lookarounds in Regex Tester
The shared lab uses the browser's JavaScript RegExp engine, so its results reflect the current runtime.
Try the example
Require USD with a lookahead
The assertion checks the suffix without including it in the numeric match.
\d+(?= USD)Expected result: Matches 10 and 30, but not 20 before EUR.
Try the example
Reject one following suffix
The negative lookahead excludes foo immediately followed by bar.
foo(?!bar)Expected result: Matches standalone foo and the foo in fooqux, but not foobar.
Try the example
Match digits after a dollar sign
A positive lookbehind checks the preceding currency marker without consuming it.
(?<=\$)\d+Expected result: Matches 10 and 30 after $, but not 20 after EUR.
Run the assertions
Test regex lookarounds
Verify actual JavaScript-engine matches against positive and negative examples.