Hone

Lessons · Regex · $ and \Z: two different ends

Two different ends

$ matches at the end of the string AND just before a newline at the end of it. \Z matches only the very end.

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

A value read from a file usually still has its newline attached, and a $-anchored check waves it through.

How to think about it

Searching text: $ is friendly and right. Validating a value: \Z, or strip the input first and say so.

Worked example

re.search(r'\w+$', 'end\n').group()
$ allowed the trailing newline.
re.search(r'\w+\Z', 'end\n')
\Z did not.
bool(re.search(r'^[a-z]+$', 'ada\n'))
So a username check that looks watertight accepts a newline.

Your turn

Say whether each of 'end' and 'end\n' ends there, with no allowance for a newline.

[bool(re.search(r'\w+', s)) for s in ('end', 'end\n')]

The trap

Every part of that last pattern is right and the check still passes something the field should never hold.

Practise $ and \Z: two different ends on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.