Lessons · Regex · anchoring so it gives up early
Telling the engine where to start
Unanchored, a failed match is retried from position 1, then 2, then 3, to the end of the line. Anchored, there is one starting position.
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
On a long line the retrying IS the cost, and it is paid on exactly the inputs that do not match -- which is what somebody attacking you sends.
How to think about it
If the match, when there is one, is always at the start, say so. It removes every other starting position at once.
Worked example
re.search(r'^\d{4}-\d{2}-\d{2}', '2026-09-09').group()One place to look, and it is there.re.search(r'^\d{4}-\d{2}-\d{2}', 'on 2026-09-09')Anchored, so this fails immediately.re.search(r'\d{4}-\d{2}-\d{2}', 'on 2026-09-09').group()Unanchored, it scanned forward and found it.Your turn
Only match a date at the very start of the line.
\d{4}-\d{2}-\d{2}Test a pattern against real text
The trap
Anchoring is a change of MEANING as well as speed. Only do it where 'at the start' is what you actually wanted.
Practise anchoring so it gives up early on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.