Regular expressions and text guides

Regex lookarounds: match text next to a condition

Use positive lookahead and lookbehind, compare them with captures, and check portability across regex engines.

Nav Tools ·

Lookarounds do not consume text

A lookahead checks the following text without making it part of the returned match. A lookbehind checks what precedes the match.

Use the example to return only 10 before USD. The currency condition is checked, but the returned text remains the number.

Input: 10 USD, 20 EUR
Pattern: \d+(?= USD)
Match: 10

Choose captures for portability

Positive lookbehind can express a prefix condition compactly in modern JavaScript. Other regex engines may reject lookbehind or support different restrictions.

A capturing group is often a portable alternative: match the prefix and extract just the desired capture. Verify the backend engine rather than assuming browser success is sufficient.

Input: item=42
Lookbehind: (?<=item=)\d+
Capture alternative: item=(\d+)

Negative conditions need boundaries

A negative lookahead excludes a local condition at its current position. It does not automatically exclude every occurrence anywhere in the whole input.

Test a forbidden word at the start, middle and end. Include a near miss so the intended scope of exclusion stays explicit.

Keep conditions inexpensive

Combining multiple lookarounds with ambiguous quantifiers can be difficult to review and expensive on long inputs. Simpler staged checks are often clearer.

Use short fixtures first, then test a long near miss under limits. Nav Tools’ worker timeout protects the page but does not certify production performance.

References

← Regular expressions and text guides