Anchors and Word Boundaries
Use ^ and $ to validate whole strings or lines, apply the multiline flag, and match whole words with word boundaries instead of fragments.
Welcome back!
Step 1 of 12Learn
Matching positions, not characters
A sign-up form accepts usernames of 3 to 16 lowercase letters, digits or underscores. A developer writes [a-z0-9_]{3,16} and tests it with "maya_22." It works. Then someone signs up as "<script>maya_22</script>" and it's accepted too. Why? The pattern found "maya_22" inside the input and reported success. It never checked the rest.
Anchors fix this. They don't match characters; they match positions:
^matches at the start of the string.$matches at the end of the string.
With both, ^[a-z0-9_]{3,16}$ means "from the very start to the very end, only 3 to 16 allowed characters." Now the script tag is rejected, and so is a username with a trailing space.
This distinction, finding versus validating, is the most important idea in this lesson. To find dates inside a log line, you want an unanchored pattern. To check that a form field is a date, and nothing else, anchor both ends. Forgetting anchors in validation code is one of the most common regex security bugs, because it lets extra input slip through alongside a valid-looking fragment.
Step 2 of 12Compare
Anchors change what "valid" means
| Aspect | [a-z0-9_]{3,16} | ^[a-z0-9_]{3,16}$ |
|---|---|---|
| maya_22 | Match | Match |
| <script>maya_22</script> | Match (finds "script") | No match |
| hi there | Match (finds "there") | No match |
| ab | No match | No match |
Step 3 of 12Practice · Choose one
A form validates phone numbers with \d{3}-\d{4} (no anchors). Which input is wrongly accepted?
Step 4 of 12Learn
Lines and the multiline flag
By default, ^ and $ refer to the start and end of the whole string, even if it contains many lines. Often you want them to work per line, for example to find log lines that start with "ERROR."
The multiline flag (m in JavaScript, re.MULTILINE in Python) changes the anchors: ^ matches at the start of every line and $ at the end of every line.
const log = "INFO start\nERROR disk full\nINFO retry\nERROR timeout";
log.match(/^ERROR.*$/gm);
// ["ERROR disk full", "ERROR timeout"]Without m, ^ERROR would only check the very beginning of the string, which starts with "INFO," so it would find nothing.
Some engines also offer \A and \z (or \Z), which always mean the absolute start and end of the string regardless of the multiline flag. Python, Ruby, Java and PCRE support them; JavaScript does not.
A small trap: in Python and several other flavors, $ also matches just before a final newline, so ^\d+$ accepts "123\n." That's usually harmless, but if you're validating input that must not contain a newline, use \z where available, or Python's re.fullmatch, covered later.
Step 5 of 12Practice · Work it out
A string contains these four lines: "ERROR a", "INFO b", "ERROR c", "WARN ERROR d". How many matches does /^ERROR/gm find?
Step 6 of 12Learn
Word boundaries
Searching for the word "cat" with cat also finds "concatenate," "education" and "cats." To match the whole word, use the word boundary anchor \b.
\b matches a position where one side is a word character (\w: letter, digit or underscore) and the other side is not, or is the start or end of the text. So \bcat\b matches "cat" in "the cat sat" and "cat!" but not in "concatenate" or "cats."
Its opposite, \B, matches any position that is not a word boundary: \Bcat\B finds "cat" only in the middle of a word, as in "education."
Some practical uses:
- Find a variable name in code without hitting longer names:
\bcount\bskips "counter" and "account." - Find standalone numbers:
\b\d+\bmatches "42" in "page 42," but not the digits inside "A42B," because they sit between word characters.
Because \b relies on \w, its idea of a "word" is ASCII letters, digits and underscore in many flavors. A hyphen counts as a boundary, so \bwell\b matches inside "well-known." And with accented text, \b can split words in unexpected places, such as before the "é" in "café" in JavaScript without Unicode-aware handling.
Step 7 of 12Compare
cat vs. \bcat\b
| Aspect | cat | \bcat\b |
|---|---|---|
| the cat sat | Match | Match |
| concatenate | Match | No match |
| cats | Match | No match: s is a word character |
| a cat. | Match | Match: the dot is not a word character |
Step 8 of 12Practice · Sort into groups
Does \bcar\b find a match in each text?
Tap an item, then tap its group (or drag it there).
Step 9 of 12Note
Step 10 of 12Practice · Code challenge
Write isUsername(name) that returns true only if the whole string is 3 to 16 characters long and contains only lowercase letters, digits and underscores.
isUsername("maya_22")isUsername("ab")isUsername("Maya")isUsername("<b>maya</b>")isUsername("a_very_long_name_123")isUsername("dev_ops")
Step 11 of 12Tap to reveal
Zero-width assertions at a glance
^and$Match at the start and end of the string, or of each line with the multiline flag. Use them for validation so nothing extra can sneak in before or after.
\bMatches where a word character meets a non-word character or the edge of the text. Use it to find whole words and standalone numbers.
\BMatches anywhere that is not a word boundary, such as between two letters. Useful for finding text in the middle of words.
Lookarounds
Check what comes before or after a position without consuming it. They are covered in module 4 and follow the same zero-width idea.
Why zero-width matters
Assertions add conditions without adding characters to the match, so the matched text stays exactly what you want to extract or replace.
Step 12 of 12Practice · Choose one
Which pattern finds the word "is" in "This is it" but not the "is" inside "This"?
Lesson complete!