Python 什么';当使用正则表达式';s.groups()函数

Python 什么';当使用正则表达式';s.groups()函数,python,exception,python-2.7,nonetype,try-except,Python,Exception,Python 2.7,Nonetype,Try Except,我正在尝试使用以下代码: try: clean = filter(None, re.match(r'^(\S+) (.*?) (\S+)$', full).groups()) except TypeError: clean = "" 但是我得到了以下回溯 Traceback (most recent call last): File "test.py", line 116, in <module> clean = filter(None, re.matc

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

try:
    clean = filter(None, re.match(r'^(\S+) (.*?) (\S+)$', full).groups())
except TypeError:
    clean = ""
但是我得到了以下回溯

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'
回溯(最近一次呼叫最后一次):
文件“test.py”,第116行,在
clean=filter(无,重新匹配(r'^(\S+)(.*?(\S+)$),完整).groups())
AttributeError:“非类型”对象没有属性“组”
解决此问题的正确例外/正确方法是什么?

尝试以下方法:

clean = ""
regex =  re.match(r'^(\S+) (.*?) (\S+)$', full)
if regex:
    clean = filter(None, regex.groups())
问题是,
re.match(r'^(\S+)(.*?(\S+)$),full)
如果未找到匹配项,则返回一个
None
。因此出现了错误


注意:您不需要使用
try.。除非以这种方式处理。

re.match
如果找不到匹配项,则返回
None
。也许解决这个问题最干净的方法就是这样做:

# 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 = ""
请注意,如果匹配:
,您也可以执行
,但我个人喜欢执行
,如果匹配不是无:
,因为它更清晰。“显性比隐性好”记住


我认为使用try,catch处理AttributeError是一个更干净的解决方案。 在行上执行的任何转换都可能是非常昂贵的操作。例如

match = re.match(r'^(\S+) (.*?) (\S+)$', full)
如果匹配项不是无: clean=筛选器(无,匹配.groups()) 其他: clean=“”


在上述情况下,行的结构发生了变化,正则表达式提供了部分结果。因此,现在match将不是none,并且将抛出AttributeError异常。

您需要将
AttributeError添加到您的exception子句中

except子句可以将多个异常命名为带括号的元组:

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

通常
re
match在没有匹配的情况下抛出
AttributeError
found@SivaCn不它返回
None
。OP然后尝试访问返回值的
属性,即
。因此,
属性错误
my_match = re.match(r'^(\S+) (.*?) (\S+)$', full)
my_match = ''
if my_match is not None:
     clean = my_match.groups()
match = re.match(r'^(\S+) (.*?) (\S+)$', full)
try:
    clean = filter(None, re.match(r'^(\S+) (.*?) (\S+)$', full).groups())
except (TypeError, AttributeError):
    clean = ""