Learn regular expressions · Lesson 6

Anchors and word boundaries

Everything so far has matched characters. An anchor matches a position between them, and takes up no text. The two most used are ^, the start, and $, the end.

The whole string

Without anchors a pattern matches anywhere, so \d{4} finds four digits inside a longer number, which is wrong if you’re checking that something is a year:

/\d{4}/1 match
123456
Try it in Dotstar →

Anchored at both ends, it has to be the whole text:

/^\d{4}$/No matches
123456
Try it in Dotstar →
/^\d{4}$/1 match
2026
Try it in Dotstar →

That’s how a regex validates input: ^…$ around the pattern. Leave one out and anything can come before or after.

Every line: the m flag

With the m flag (multiline), ^ and $ match at the start and end of every line, not only of the whole text:

/^\d{4}$/gm2 matches
2026
12345
abcd
1999
Try it in Dotstar →

The m flag has nothing to do with the dot: the dot-all flag, s, from the lesson on the dot, decides whether . takes line breaks. The two are independent, and can be used together.

The real end: \A and \z

In most engines $ without m also matches just before a line break at the very end, so ^\d{4}$ accepts "2026\n". Usually harmless, sometimes not: a value that should be four digits gets a line break in with it. \A and \z are the start and end of the text and nothing else, whatever the flags.

Word boundaries: \b

\b is the position between a word character (\w: a letter, a digit or an underscore) and anything else, or the start or end of the text. So \bcat\b is cat as a whole word:

/\bcat\b/g2 matches
cat concatenate cats bobcat cat.
Try it in Dotstar →

\B is the opposite: a position inside a word. \Bcat\B finds cat only in the middle of one.

Because \b is defined by \w, it follows \w’s idea of a letter. In JavaScript that’s ASCII, so \b sees a boundary inside café before the é; in engines where \w is Unicode, it doesn’t. The lesson on character classes has the list.