Skip to content

Lesson 6 of 13 · 20m

Lookarounds: Matching on Context Without Consuming It

Lookahead and lookbehind as zero-width assertions, engine support differences, and when a lookaround is cleverness you should replace with code.

Lookarounds let a pattern ask "what's next to me?" without putting the answer in the match. They're the strongest construct in Perl-style regex and the most abused. Used well they make a replacement surgical. Used badly they turn a validation rule into an unreadable wall nobody dares touch.

Four assertions, zero width

  • X(?=Y) — positive lookahead: X, only if followed by Y
  • X(?!Y) — negative lookahead: X, only if not followed by Y
  • (?<=Y)X — positive lookbehind: X, only if preceded by Y
  • (?<!Y)X — negative lookbehind: X, only if not preceded by Y

"Zero-width" is the entire idea: the engine checks the condition, then returns to the exact position it started from. Nothing is consumed and nothing lands in match[0].

The cursor doesn't move

const withCommas = n => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(withCommas(1234567));   // 1,234,567
console.log(withCommas(999));       // 999

Read it as "a non-word-boundary position followed by groups of exactly three digits, followed by a non-digit." The match is an empty string at each insertion point; the replacement drops a comma there. A good party trick. In production, new Intl.NumberFormat("en-US").format(n) does the same job and also knows India groups digits as 12,34,567 — your regex does not.

Lookbehind for surgical replacement

const log = "POST /login user=alice password=hunter2&remember=1";
console.log(log.replace(/(?<=password=)[^&\s]+/g, "[REDACTED]"));
// POST /login user=alice password=[REDACTED]&remember=1

Without lookbehind you'd capture password= and re-insert it with $1. The lookbehind version states intent directly: replace the value, keep the key.

Negative lookahead: the exclusion case

const files = ["app.js", "app.min.js", "vendor.js", "vendor.min.js"];
console.log(files.filter(f => /^(?!.*\.min\.js$).+\.js$/.test(f)));
// ["app.js", "vendor.js"] — .js files that don't end in .min.js

(?!.*\.min\.js$) asserts "this position is not followed by a string ending in .min.js." Readable enough at one lookahead. Three lookaheads deep it becomes the password-policy wall below.

The other classic is "match X only when not preceded by Y" — (?<!\\)% matches a percent sign that wasn't escaped, and (?<!https?:)// catches protocol-relative links. These work because the assertion inspects raw context, not grammar.

Support varies more than anything else in the spec

  • JavaScript (ES2018+): arbitrary-length lookbehind — (?<=Bearer\s+)\S+ works.
  • Python re: lookbehind must be fixed width; that pattern raises re.error: look-behind requires fixed-width pattern. The third-party regex module relaxes this.
  • PCRE2 and Java: bounded-length lookbehind — \s{1,3} yes, \s+ no.
  • RE2, Go, grep -E, ripgrep's default engine, Prometheus: no lookarounds at all. Reach for grep -P or rg -P.

The password-policy trap

^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^\w\s]).{12,64}$

It works, and it's bad engineering. The user gets one "invalid password" instead of "add a digit"; each (?=.*X) rescans the input from position zero; and NIST SP 800-63B discourages composition rules entirely in favor of length plus breach-list screening. Four separate test() calls give you per-rule error messages, faster failure, and code your successor can read.

Overlapping matches with a lookahead wrapper

console.log([..."ababa".matchAll(/(?=aba)/g)].length);   // 2 — positions 0 and 2

Because the lookahead consumes nothing, matchAll advances one position per match. Wrapping a pattern in (?=...) is the standard way to count overlapping occurrences — and a good demonstration of why zero-width constructs behave differently from everything else in the engine.

Field notes

  • Lookarounds are atomic in Perl-style engines: once satisfied, the engine never backtracks inside them. Captures inside a lookahead freeze at first success.
  • "Lines not containing X" is grep -v X, not ^(?!.*X).*$. Pipeline beats pattern.
  • Because nothing is consumed, lookarounds match at overlapping positions — great for counting overlaps, surprising everywhere else.
  • If a pattern needs three lookaheads to express a business rule, it wants to be three lines of code.

Keep reading

Related articles from the SudoSecurity blog.