使用正则表达式的.groups()函数时,NoneType的正确尝试异常是什么

Ryf*_*lex 8 python exception python-2.7 try-except nonetype

我正在尝试使用以下代码:

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

但是我得到了以下追溯......

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'
Run Code Online (Sandbox Code Playgroud)

围绕这个问题的正确异常/正确方法是什么?

iCo*_*dez 21

re.matchNone如果找不到匹配则返回.解决这个问题最简洁的方法就是这样做:

# 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 = ""
Run Code Online (Sandbox Code Playgroud)

请注意,您也可以这样做if match:,但我个人喜欢这样做,if match is not None:因为它更清晰."明确胜过隐性"记住.;)


Pac*_*aco 8

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'
Run Code Online (Sandbox Code Playgroud)

它告诉您要处理的错误:AttributeError

它是:它是:

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

要么

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


kar*_*ikr 5

尝试这个:

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

问题是,如果没有找到匹配项,re.match(r'^(\S+) (.*?) (\S+)$', full)则返回 a 。None因此出现了错误。

try..except注意:如果您这样处理,则不需要 a 。