Concept

Anchors: ^ and $ Explained

Anchors match positions, not characters. ^ asserts the start of the string (or line, with the m flag) and $ asserts the end.

What they do

An anchor is a zero-width assertion — it matches a position between characters rather than a character itself. ^ matches the position before the first character of the input. $ matches the position after the last character. They are the primary tool for whole-string validation: wrap a pattern in ^…$ and it only matches if the ENTIRE string conforms.

Whole-string vs. anywhere matching

Without anchors, a regex matches any substring. With ^ and $ at both ends, it only matches when the full input fits the pattern. This is the difference between 'find a digit somewhere' and 'the whole input is exactly digits.'

Unanchored — matches inside a longer string

Try this
/\d+/

Input

order 4242 received

Result

Match: 4242

Anchored — requires whole input is digits

Try this
/^\d+$/

Input

order 4242 received

Result

No match

Anchored — matches cleanly when input fits

Try this
/^\d+$/

Input

4242

Result

Match: 4242

With the multiline (m) flag

When the m flag is set, ^ and $ also match at the start and end of each line within the input (around every \n). Without m, they only match at the absolute start and end of the string.

Common uses

Form input validation (require the entire value to match), parsing line-oriented formats like log files (with m), and rejecting leading/trailing whitespace when trimming wasn't done upstream.

Related patterns

All reference guidesOpen the RegexPro tester →