LOOKAROUNDS

Lookahead

Assert what follows a position without consuming it.

A lookahead is a condition, not a match. \d+(?=px) matches digits ONLY if "px" comes right after, but the px stays out of the match. In "10px" it matches "10" and leaves the px alone.

\d(?=px) positive lookahead: a digit only if "px" follows. In "5px" matches the 5; in "5em" matches nothing.
\d(?!px) negative lookahead: a digit only if "px" does NOT follow. In "5em" matches the 5; in "5px" matches nothing.

Because lookarounds consume nothing, they let separate conditions stack on the same spot: ^(?=.*\d)(?=.*[a-z]) asserts a line contains a digit somewhere and a lowercase letter somewhere - the classic password check shape. To assert what comes BEFORE a position instead, reach for lookbehind.

PRACTICE - 3 DRILLS 0/3 DONE
DRILL 1/3

Match every number that is immediately followed by px. The px itself must not be part of the match.

/ /
width: 10px; top: 5em; gap: 3px
must match: "10" "3"
size 20pt
must match nothing
8px 9px
must match: "8" "9"
DRILL 2/3- Negative lookahead

Match foo only when it is NOT immediately followed by bar.

/ /
foobar foobaz foo
must match: "foo" "foo"
foofoo
must match: "foo" "foo"
foobar
must match nothing
DRILL 3/3- Contains a digit

Match a whole non-empty line only if it contains at least one digit somewhere. Assume each test string is a single line.

/ /
abc1
must match: "abc1"
a1b2
must match: "a1b2"
hello
must match nothing
must match nothing