Hone

Lessons · Regex · the pattern you will have to read again

The pattern you will have to read again

VERBOSE for a comment on each part, named groups so the code reads by meaning rather than by 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

A number is a position; a name is a meaning. Somebody adds a bracket and every number after it changes, while the names go on saying what they said.

How to think about it

If a pattern needs a paragraph of explanation, it is usually two patterns with a line of code between them. Splitting it is allowed.

Worked example

re.search(r'(?P<user>\w+)@(?P<host>\w+)', 'ada@work').group('host')
Read by name.
re.search(r'(?P<user>\w+)@(?P<host>\w+)', 'ada@work').groupdict()
Or all of them at once, already labelled.
re.search(r'(\w+)@(\w+)', 'ada@work').group(2)
The same thing by position, which the next bracket will break.

Your turn

Say what the four digits in this pattern are for.

r'''\d{4}   # '''

The trap

A comment ABOVE a pattern drifts from it the first time somebody edits one and not the other. Inside, each comment sits on the part it describes.

Practise the pattern you will have to read again on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.