Advertisement

Line Anchors

Match at line start or end.

^           # Start of line
$           # End of line
^abc        # Line starts with "abc"
xyz$        # Line ends with "xyz"
^abc$       # Entire line is "abc"

Word Boundaries

Match at word boundaries.

\b          # Word boundary
\B          # Non-word boundary
\bcat\b     # Match "cat" as whole word
\Bcat\B     # Match "cat" not at boundaries

Start of String

Match beginning of string.

^           # Start of string (in multiline mode: line)
\A          # Start of string (always)
Advertisement

End of String

Match end of string.

$           # End of string (in multiline mode: line)
\Z          # End of string (always)
\z          # Absolute end of string

Word Boundary Examples

Matching whole words.

\bword\b     # Match "word" as whole word
\btest       # Match "test" at start of word
test\b       # Match "test" at end of word
\b\w{4}\b    # Match any 4-letter word

Line Anchor Examples

Match at specific line positions.

^\d          # Line starts with digit
\.$          # Line ends with period
^$           # Empty line
^\s*$        # Blank line (only whitespace)

Combining Anchors

Use multiple anchors together.

^\w+$        # Entire line is word characters
^https?://   # Line starts with http:// or https://
\.com$       # Line ends with .com
^\d{3}-\d{4}$ # Entire line is phone format

Practical Examples

Real-world anchor usage.

^\#          # Line starts with # (markdown heading)
^import      # Python import at line start
;\s*$        # Line ends with semicolon
^\s+         # Leading whitespace
\s+$         # Trailing whitespace
Last updated: January 2026
Advertisement