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

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

转载于:https://www.cnblogs.com/huahuayu/p/8253882.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值