python中re匹配时,匹配0个字符串,也算匹配上

re.match(r'\d*', "NIL")
<_sre.SRE_Match object; span=(0, 0), match=''>

上面的表达式本来想过滤数字或非数字的字符串,用于将数字字符串转为int()。


但是匹配结果虽然没有在‘NIL’中找到数字,但还是匹配上了,返回结果时对象,而不是NONE。正常情况不匹配时应该返回NONE,但它匹配了0个字符串,原因是:

re*匹配0个或多个的表达式。

应该使用:

re.match(r'\d+', "NIL")

re+匹配1个或多个的表达式。


re. match ( pattern, string, flags=0 )

If zero or more characters at the beginning of string match the regularexpression pattern, return a corresponding MatchObject instance.Return None if the string does not match the pattern; note that this isdifferent from a zero-length match.

https://docs.python.org/2/library/re.html#re.match

猜你喜欢

转载自blog.csdn.net/qq_27361945/article/details/80504991