Positive Lookahead

Assert that pattern is followed by another.

(?=...)         # Positive lookahead
\d(?=px)        # Digit followed by "px"
\w+(?=@)        # Word before @
test(?=ing)     # "test" followed by "ing"

Negative Lookahead

Assert that pattern is NOT followed by another.

(?!...)         # Negative lookahead
\d(?!px)        # Digit NOT followed by "px"
\w+(?!@)        # Word NOT before @
test(?!ing)     # "test" NOT followed by "ing"

Positive Lookbehind

Assert that pattern is preceded by another.

(?<=...)        # Positive lookbehind
(?<=\$)\d+      # Digits after $
(?<=@)\w+       # Word after @
(?<=Mr\.)\w+    # Word after "Mr."

Negative Lookbehind

Assert that pattern is NOT preceded by another.

(?<!...)        # Negative lookbehind
(?<!\$)\d+      # Digits NOT after $
(?<!@)\w+       # Word NOT after @
(?<!un)\w+      # Word NOT after "un"

Combining Lookarounds

Use multiple assertions together.

(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}
# Password: lowercase, uppercase, digit, 8+ chars

(?<=<)(?!/)(\w+)(?=>)
# HTML opening tag name

\b(?!cat|dog)\w+\b
# Word not "cat" or "dog"

Practical Examples

Real-world lookaround usage.

(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}
# Strong password validation

(?<=\$)\d+\.?\d*
# Dollar amount without $

\b\w+(?=\.com)
# Domain name before .com

(?<!\/\/).*(?=:)
# Protocol in URL

(?!.*test).*
# Line not containing "test"

Password Validation

Complex password requirements.

(?=.*[a-z])         # At least one lowercase
(?=.*[A-Z])         # At least one uppercase
(?=.*\d)            # At least one digit
(?=.*[@$!%*?&])     # At least one special char
.{8,}               # At least 8 characters

Combined:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

Common mistakes / Pitfalls

  • People often copy a command or pattern without adapting placeholders, which can break production workflows unexpectedly.
  • It is easy to forget environment-specific differences, so always verify behavior in your shell, runtime, or API gateway before shipping.
  • Many errors come from skipping small validation steps, so test with realistic sample input before relying on the result.
Last updated: February 2026