Regex · <code>^</code> — string start, or line start with the m flag

Anchors and word boundaries

Anchors match positions, not characters: ^ and $ for line or string edges, \b for a word boundary.

Key facts

Start<code>^</code> — string start, or line start with the m flag
End<code>$</code> — string end, or line end with the m flag
Word boundary<code>\b</code> — between a word character and a non-word character
Non-boundary<code>\B</code>
MultilineFlag <code>m</code>
PCRE absolute<code>\A</code> and <code>\z</code>
JavaScriptNo \A or \z anchor
Zero widthAnchors consume no characters

Positions, not text

^ and $ assert a position. Without the multiline flag they refer to the start and end of the whole input; with m they also match after and before a newline. This is why the same pattern suddenly matches every line once the flag is added.

Some engines also let $ match just before a final newline. That leniency is convenient for files and surprising for validation: if a trailing newline must be rejected, anchor with the absolute end assertion where the engine provides one.

Word boundaries depend on the word class

\b is a position between a word character and a non-word character, using the engine's definition of word characters. In JavaScript that is ASCII letters, digits and underscore, so a boundary before an accented letter may not exist where you expect. Treat boundary matching as an ASCII-oriented tool.

Anchoring also affects performance: a pattern that starts with ^ gives the engine one starting position instead of many, which is often the cheapest way to make a slow regex fast.

Frequently asked questions

What does ^ mean in a regex?

It asserts the start of the input, or the start of a line when the multiline flag is active. Inside a character class it means negation instead.

Does \b match a space?

No. It matches the position between a word character and a non-word character, consuming nothing.

How do I match the absolute end of a string in JavaScript?

Use an anchor that cannot be satisfied earlier in the pattern, or test that the match ends at input.length. JavaScript has no \z equivalent.

New tools, straight to your inbox

One short email when we add tools worth using. No spam, unsubscribe anytime.