Hone

Lessons · Regex · VERBOSE: a pattern with room to breathe

A pattern with room to breathe

Under VERBOSE, whitespace in the pattern is ignored and # starts a comment, so a long pattern can be laid out with a note on each part.

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 pattern nobody can read is rewritten from scratch by the next person, bugs and all. This is the cheapest way to make one readable.

How to think about it

One part per line, a comment saying what that part is for. It changes nothing about what matches -- only how the pattern may be written.

Worked example

re.search(r'\d+ # the count', 'x42', re.X).group()
The space and the comment are laid out, not matched.
re.search(r'a b', 'ab', re.X).group()
The space in the pattern is gone, so this matches 'ab'.
re.search(r'a\ b', 'a b', re.X).group()
A space you MEANT has to be escaped, or put in a class.

Your turn

Let the pattern carry a comment.

re.search(r'\d+ # the count', 'x42', re.).group()

The trap

That second line is the trap inside the flag: turning on VERBOSE silently deletes every space you wrote on purpose.

Practise VERBOSE: a pattern with room to breathe on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.