在以下代码中,我们不确定match
方法(p.match
)的输入是什么,因此结果可能是None
,例如:
>>> import re
>>> p = re.compile('[a-z]+')
>>> p.match("").group(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
在group
方法返回时直接应用match
方法是否可以?为什么Python允许这样做,即使p.match
可以return None
?
答案 0 :(得分:2)
您无法理解Python的工作原理。 无法知道对象实际上存在之前没有该名称的方法。因此,如果您没有获得预期的对象,请确保您不要尝试调用该方法。
答案 1 :(得分:1)
您的正则表达式与输入的空字符串不匹配,因为[a-z]+
匹配一个或多个小写字母。
因为没有匹配发生,它会显示如上所述的错误。
>>> p = re.compile('[a-z]*')
>>> p.match("").group()
''
这显示匹配,因为*
重复前一个标记零次或多次。
答案 2 :(得分:1)
re.match
在没有匹配的情况下返回None
的原因是它使以下工作正常:
if re.match(pattern, string):
# do whatever with the string
正如the documentation所说:
如果字符串与模式不匹配,则返回
None
;请注意,这与零长度匹配不同。
match
对象将始终在布尔上下文中评估truth-y,而None
评估false-y。
Python没有阻止你编写re.match(...).group(...)
的原因是,在代码实际运行之前,很难说出re.match(...)
可以返回的内容:你可能已经重新定义{{1} }或猴子修补re
;这些论点没有提前知道;等等。这是因为在打字和内省方面,Python是一种非常动态的语言。
因此,您有两个选项,look before you leap:
match
或ask forgiveness rather than permission:
match = re.match(...)
if match:
match.group(...)