Regex Lookahead and Lookbehind Assertions Explained

Complete guide to regex lookahead (?=), negative lookahead (?!), lookbehind (?<=), and negative lookbehind (?<!). Zero-width assertions with examples.

Assertions

Detailed Explanation

Lookahead and Lookbehind Assertions

Lookaround assertions check for patterns ahead or behind the current position without including them in the match. They are "zero-width" — they assert a condition without consuming characters.

The Four Types

Syntax Name Checks
(?=...) Positive lookahead What follows matches
(?!...) Negative lookahead What follows does NOT match
(?<=...) Positive lookbehind What precedes matches
(?<!...) Negative lookbehind What precedes does NOT match

Positive Lookahead (?=...)

Matches a position where the pattern inside the lookahead can be matched next. The lookahead itself consumes no characters.

Example: \w+(?=@) matches the username portion of an email address. In user@example.com, it matches user without including the @.

Negative Lookahead (?!...)

Matches a position where the pattern inside CANNOT be matched next.

Example: \d+(?!px) matches numbers NOT followed by px. In 100em 200px 300rem, it matches 100 and 300 but not 200.

Positive Lookbehind (?<=...)

Matches a position preceded by the specified pattern.

Example: (?<=\$)\d+ matches digits preceded by a dollar sign. In Price: $100, it matches 100.

Negative Lookbehind (?<!...)

Matches a position NOT preceded by the specified pattern.

Example: (?<!\d)px matches px not preceded by a digit. Useful for finding CSS units used incorrectly.

Browser Support

All modern browsers support lookbehind assertions (ES2018+). Older environments may only support lookahead. Always check your target platform.

Use Case

You need to match patterns only when they appear in a specific context, such as extracting prices only when preceded by a currency symbol, matching words not followed by certain punctuation, or validating password complexity rules.

Try It — Regex Cheat Sheet

Open full tool