Hone

Lessons · Regex · testing it on what nearly matches

Test it on what nearly matches

Anything obviously right passes a pattern that is far too loose. The near miss is where the boundary actually is, and a boundary is what a pattern is.

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

Real data is mostly near misses: a trailing space, a Unicode dash instead of a hyphen, a newline from a file read. Each is one character away from what you tried.

How to think about it

For every valid example, write the one that is a character too long, a character short, and the right shape with a wrong character in it.

Worked example

[bool(re.fullmatch(r'\d{4}', s)) for s in ('2026', '20267')]
One too long is refused.
[bool(re.fullmatch(r'\d{4}', s)) for s in ('2026', '2026 ')]
And so is a trailing space -- because fullmatch was used.
[bool(re.match(r'\d{4}', s)) for s in ('2026', '20267')]
With match instead, the too-long one gets in.

Your turn

Name a near miss you would test a four-digit year against.

test: '2026'

The trap

Valid values only show the pattern is not too STRICT. The near misses are the half that shows it is not too loose.

Practise testing it on what nearly matches on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.