背景图
Regex Lookarounds

2025年10月12日 作者头像 作者头像 ArnoX 编辑

Regex.jpg


Regular expressions (regex) are incredibly powerful for text pattern matching, but sometimes we need to match a pattern only when it’s preceded or followed by something specific — without including that condition in the result.
That’s where lookarounds come in.

Lookarounds are zero-width assertions, meaning they check context (ahead or behind) but don’t consume any characters.
There are four types of lookarounds:

  • Positive Lookahead (?=...)
  • Negative Lookahead (?!...)
  • Positive Lookbehind (?<=...)
  • Negative Lookbehind (?<!...)

1. Positive Lookahead (?=...)

A positive lookahead checks if the given pattern is followed by another specific pattern.
It matches the content before the lookahead, but not the part inside (?=...)

positive lookahead.png

2. Negative Lookahead (?!...)

A negative lookahead checks that the given pattern is not followed by a specific sequence.

negative lookahead.png

3. Positive Lookbehind (?<=...)

A positive lookbehind checks if the given pattern is preceded by another specific pattern.

positive lookbehind.png

4. Negative Lookbehind (?<!...)

A negative lookbehind checks that the given pattern is not preceded by a specific sequence.

negative lookbehind.png