Regex Anchors — ^, $, \b Word Boundaries Explained
Master regex anchors: ^ for start of string, $ for end of string, \b for word boundaries, and \B for non-word boundaries. Control where patterns match.
Detailed Explanation
Regex Anchors and Boundaries
Anchors do not match characters — they match positions in the string. They ensure your pattern matches at the right location.
Start and End Anchors
| Anchor | Position |
|---|---|
^ |
Start of string (or line with m flag) |
$ |
End of string (or line with m flag) |
Without anchors, \d+ matches digits anywhere in the string. With anchors, ^\d+$ only matches if the ENTIRE string is digits.
Multiline Mode
With the m flag, ^ and $ match the start and end of each line rather than the entire string:
Input: "line 1\nline 2\nline 3"
Pattern: ^line (with m flag)
Matches: "line" at the start of each line (3 matches)
Word Boundaries \b
The \b anchor matches the boundary between a word character (\w) and a non-word character (\W), or between a word character and the start/end of the string.
Pattern: \bword\b
Matches: "word" in "a word here"
Skips: "sword", "wordy", "keyword"
This is invaluable for matching whole words without accidentally matching substrings.
Non-Word Boundaries \B
\B matches any position that is NOT a word boundary. It matches inside words.
Pattern: \Bword
Matches: "word" in "sword" (inside the word)
Skips: "word" at the start of a string
Common Anchor Patterns
^$— matches an empty string or empty line^\s*$— matches a blank line (whitespace only)\b\w{5}\b— matches exactly 5-letter words^(?!#).*$— matches lines that do not start with#(withmflag)
Use Case
You need to validate that an entire input matches a pattern (like a phone number or zip code), find whole words without matching substrings, or process text line by line in multiline mode.