What is the correct Try exception for NoneType when using the regex.groups () function

I am 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 trace ...

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 to solve this problem?

+4
source share
5 answers

re.matchreturns Noneif it cannot find a match. Probably the cleanest solution to this problem is simply:

# 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 = ""

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

+11
source
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'

, : AttributeError

:

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

my_match = re.match(r'^(\S+) (.*?) (\S+)$', full)
my_match = ''
if my_match is not None:
     clean = my_match.groups()
+5

:

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

, re.match(r'^(\S+) (.*?) (\S+)$', full) a None, . .

: try..except, .

+4

, AttributeError try, catch - . , . .

match = re.match(r'^(\S+) (.*?) (\S+)$', full)

None:   clean = filter (, match.groups()) :   clean = ""

in the above case, the string structure has changed so that the regular expression delivers a partial result. So now the match will not be anything and an AttributeError exception will be thrown.

0
source

You need to add AttributeErrorexceptions to your proposal.

The except clause may contain several exceptions in parentheses in brackets:

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

All Articles