Hone

Lessons · Regex · ^ and $ anchors

Pin the pattern to the edges

^ matches the start of the text, $ the end. Together they mean 'the whole thing must be this'.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Validation without anchors accepts anything that merely contains a valid value.

How to think about it

Is this 'is valid' or 'contains'? For 'is this a valid X', always anchor both ends. For 'does it contain X', do not.

Worked example

pattern: ^[a-z]+$
Only lowercase letters, nothing else.
text: hello
Match.
text: hello1
No match: the 1 is not allowed before the end.

Your turn

Whole string is exactly three digits.

^\d{3}

The trap

With the m flag, ^ and $ match at line breaks too. Without it, only at the ends of the whole text.

Practise ^ and $ anchors on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.