Anchors and Boundaries

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

Overview

Control where matches occur using anchors and word boundaries

01 Start Anchor

The caret ^ anchor matches the start of a line (with MULTILINE flag) or string.

Pattern breakdown:

  • ^Hello - "Hello" must be at the start of a line

This matches only lines that begin with "Hello", not "Hello" appearing elsewhere.

Source: Regular-Expressions.info - Anchors

Pattern: ^Hello
Test Input
Hello World
Say Hello
Hello there
hello
Match Results
Line 1: "Hello World"
Match 1: "Hello"
Line 2: "Say Hello" - No match
Line 3: "Hello there"
Match 1: "Hello"
Line 4: "hello" - No match
All matches found: 2
Matches: ['Hello', 'Hello']

02 End Anchor

The dollar sign $ anchor matches the end of a line or string.

Pattern breakdown:

  • \. - literal period (escaped because . is a special character)
  • $ - must be at end of line

This matches only lines ending with a period.

Source: Python Regex HOWTO

Pattern: \.$
Test Input
This is a sentence.
Another sentence
End with period.
No period here
Match Results
Line 1: "This is a sentence."
Match 1: "."
Line 2: "Another sentence" - No match
Line 3: "End with period."
Match 1: "."
Line 4: "No period here" - No match
All matches found: 2
Matches: ['.', '.']

03 Word Boundary

The \b word boundary matches the position between a word character and a non-word character.

Pattern breakdown:

  • \bcat\b - "cat" as a complete word
  • Won't match "cat" within "catalog" or "scattered"

This is essential for finding whole words and avoiding partial matches.

Source: Regular-Expressions.info - Word Boundaries

Pattern: \bcat\b
Test Input
I have a cat.
The catalog is here.
cat
scattered cats
Match Results
Line 1: "I have a cat."
Match 1: "cat"
Line 2: "The catalog is here." - No match
Line 3: "cat"
Match 1: "cat"
Line 4: "scattered cats" - No match
All matches found: 2
Matches: ['cat', 'cat']