What's the correct Try Exception for NoneType when using regex's .groups() function

Ryflex picture Ryflex · Oct 25, 2013 · Viewed 58.2k times · Source

I'm trying to use the following code:

try:
    clean = filter(None, re.match(r'^(\S+) (.*?) (\S+)$', full).groups())
except TypeError:
    clean = ""

However I get the following traceback...

Traceback (most recent call last):
  File "test.py", line 116, in <module>
    clean = filter(None, re.match(r'^(\S+) (.*?) (\S+)$', full).groups())
AttributeError: 'NoneType' object has no attribute 'groups'

What is the correct exception / correct way around this problem?

Answer

user2555451 picture user2555451 · Oct 25, 2013

re.match returns None if it cannot find a match. Probably the cleanest solution to this problem is to just do this:

# There is no need for the try/except anymore
match = re.match(r'^(\S+) (.*?) (\S+)$', full)
if match is not None:
    clean = filter(None, match.groups())
else:
    clean = ""

Note that you could also do if match:, but I personally like to do if match is not None: because it is clearer. "Explicit is better than implicit" remember. ;)