Hone

Lessons · Regex · a failed search hands back None

Nothing is None, not empty

A search that finds nothing hands back None, and None has no .group().

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

It is the commonest crash in code that uses regex: AttributeError: 'NoneType' object has no attribute 'group', in production, on the one input nobody tried.

How to think about it

Two lines, always: get the match, then use it only if there is one. The one-liner that reads well is the one that crashes.

Worked example

re.search(r'\d+', 'no digits')
Nothing found.
bool(re.search(r'\d+', 'no digits') is None)
Which is None, not an empty string.
bool(re.search(r'x*', 'abc'))
And a match object is always truthy, even one that matched no characters at all.

Your turn

Say whether the search came back empty-handed.

bool(re.search(r'\d+', 'no digits')  None)

The trap

Because an empty match is still truthy, `if m:` is asking 'was there a match', never 'did it match anything'. Those are different questions.

Practise a failed search hands back None on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.