SyntaxStudy
Sign Up
Python Intermediate 3 min read

Anchors

Anchors

Anchors match positions, not characters. ^ matches the start, $ the end, \b a word boundary.

Example
import re

text = "cat concatenate"
# \b matches whole words
print(re.findall(r"\bcat\b", text))  # ["cat"]

# ^ and $ with re.MULTILINE
lines = "first
second
third"
starts = re.findall(r"^\w+", lines, re.M)
print(starts)  # ["first", "second", "third"]
Pro Tip

Use re.MULTILINE to make ^ and $ match line boundaries, not just string boundaries.