您的位置:首页 > 编程语言 > Python开发

Python正则表达式返回首次匹配到的字符及查询的健壮性

2018-01-09 21:51 531 查看

re.findall(pattern,string)会搜索所有匹配的字符,返回的是一个列表,获取首个匹配需要re.findall(pattern,string)[0]访问, 但是如果findall没匹配成功则返回空列表,这时用列表下标去访问元素时就会报IndexError: list index out of range。

如:

>>>re.findall('abc','abd')
[]
>>>re.findall('abc','abd')[0]
Traceback (most recent call last):
File "<input>", line 1, in <module>
IndexError: list index out of range

 

我们可以在pattern后面加一个"|$"来生成一个默认的''元素:

>>>re.findall('abc|$','abd')[0]
''
>>>re.findall('abc|$','abcdef') #注意,无论匹配到与否,都会附加上一个''元素
['abc', '']

 

同样适用于re.search

>>> re.search('\d+|$', 'aa33bbb44').group()
'33'
>>> re.search('\d+|$', 'aazzzbbb').group()
''

 

如果不加|$的话:

>>>re.search('\d+', 'aazzzbbb').group() #search没匹配上,再用.group()就会报错
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

 

参考:https://stackoverflow.com/questions/38579725/return-string-with-first-match-regex

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: