Use Anchors and Word Boundaries
Core idea
Anchors assert positions, not characters. ^ starts a string (or line with MULTILINE), and $ can also match before a final newline. The word boundary \b separates word and non-word characters or a word edge. For whole-input checks prefer fullmatch.
import reprint(re.findall(r"\bcat\b", "cat catalog bobcat cat!"))Neither catalog nor bobcat has both required boundaries.
Check a trailing newline
import res = "OK\n"print(bool(re.search(r"^OK$",s)))print(bool(re.fullmatch("OK",s)))The dollar anchor can match before the final newline; fullmatch does not accept the unmatched newline.
Common mistake
Use raw strings for \b: in a normal Python literal, "\b" means backspace. Regex word boundaries are not full linguistic word segmentation.
Practice
Count complete occurrences of "cat" in a case-sensitive ASCII sentence.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Anchors and boundaries
Check your understanding of anchors and boundaries.
What is printed?
import reprint(re.findall(r"\bgo\b","gone go"))What is printed?
import reprint(bool(re.search(r"X$","X\n")))What does a word boundary consume?
Which literal preserves a regex word-boundary escape?