Advanced Patterns

Learn regular expressions by seeing patterns, test cases, and match results side-by-side

Overview

Use alternation and lookaround assertions for complex matching

01 Alternation

The pipe | creates alternation, matching one pattern OR another.

Pattern breakdown:

  • \b(cat|dog|bird)\b - match "cat" OR "dog" OR "bird" as whole words

This is useful for matching multiple alternatives in one pattern.

Source: Regular-Expressions.info - Alternation

Pattern: \b(cat|dog|bird)\b
Test Input
I have a cat and a dog.
Birds are nice.
The catalog has items.
Match Results
Line 1: "I have a cat and a dog."
Match 1: "cat"
Groups: 1: "cat"
Match 2: "dog"
Groups: 1: "dog"
Line 2: "Birds are nice." - No match
Line 3: "The catalog has items." - No match
All matches found: 2
Matches: ['cat', 'dog']

02 Positive Lookahead

Positive lookahead (?=...) matches a position where the pattern ahead matches, without consuming characters.

Pattern breakdown:

  • \d+ - one or more digits
  • (?= dollars) - only if followed by " dollars" (not captured)

This matches "50" and "100" but not "30" because it's followed by "euros".

Source: Regular-Expressions.info - Lookaround Assertions

Pattern: \d+(?= dollars)
Test Input
I have 50 dollars
That costs 30 euros
Price: 100 dollars
Match Results
Line 1: "I have 50 dollars"
Match 1: "50"
Line 2: "That costs 30 euros" - No match
Line 3: "Price: 100 dollars"
Match 1: "100"
All matches found: 2
Matches: ['50', '100']

03 Negative Lookbehind

Negative lookbehine (?<!...) matches a position where the pattern ahead does NOT match.

Pattern breakdown:

  • \b\w+ - word characters
  • (?!ing\b) - not followed by "ing" at word boundary

This matches "test" and "walk" but not "running" or "jumping".

Source: Python Regex HOWTO - Lookahead

Pattern: \b\w+\b(?<!ing)
Test Input
running
test
jumping
walk
Match Results
Line 1: "running" - No match
Line 2: "test"
Match 1: "test"
Line 3: "jumping" - No match
Line 4: "walk"
Match 1: "walk"
All matches found: 2
Matches: ['test', 'walk']