C.W.K.
Stream
Lesson 09 of 12 · published

Anchors — ^ and $

~8 min · anchors, start, end, multiline

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Pin the match to a position

Anchors are zero-width — they don't consume characters, they just assert that you're at a specific position.

  • ^ — start of string (or start of line, with the MULTILINE flag)
  • $ — end of string (or end of line, with MULTILINE)

Without anchors, your pattern can match anywhere. With ^pattern$, you're saying "the entire input is exactly this pattern."

The MULTILINE flag

By default, ^ and $ match the start and end of the whole string. With re.MULTILINE (Python) or the m flag (PCRE/JS), they additionally match at the start and end of every line. This matters for processing multi-line input — log files, multi-line user input, etc.

The fullmatch alternative

In Python, re.fullmatch(pat, text) is shorthand for re.match(r"^" + pat + r"$", text). Use it when you want to validate that the entire string matches a pattern. It's clearer than wrapping anchors and harder to mess up.

The \A and \Z anchors

Some flavors (Python, PCRE, .NET) provide \A and \Z as absolute string-start and string-end. They ignore MULTILINE. So \A always means "start of input," never "start of line." Useful when you want anchoring that doesn't change with flags.

Code

Anchors in practice·python
import re

# 'foo' anywhere
re.search(r'foo', 'foobar foo').group()  # 'foo'

# 'foo' as the entire string?
bool(re.fullmatch(r'foo', 'foo'))     # True
bool(re.fullmatch(r'foo', 'foobar'))  # False

# Per-line with MULTILINE
log = 'line one\nERROR: oops\nline three'
re.findall(r'^ERROR.*$', log, re.MULTILINE)
# ['ERROR: oops']

# Without MULTILINE — only matches if ERROR is at very start
re.findall(r'^ERROR.*$', log)
# []

External links

Exercise

Take a multi-line log and write three different anchor scenarios: (1) does the *file* start with a header? (2) which lines start with 'WARN'? (3) which lines END in a digit? For each, decide whether you need MULTILINE.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.