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.
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
size 20pt
8px 9px
Match foo only when it is NOT immediately followed by bar.
foobar foobaz foo
foofoo
foobar
Match a whole non-empty line only if it contains at least one digit somewhere. Assume each test string is a single line.
abc1
a1b2
hello