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
相关文章推荐
- [转]Python正则表达式中匹配GBK/UTF-8编码中文字符_绝冬之地_百度空间
- python正则表达式匹配[]中间为任意字符
- Python从文件中读取字符串,用正则表达式匹配中文字符的问题
- Python:正则表达式匹配任意字符(包括换行符)的写法
- Python:正则表达式匹配任意字符(包括换行符)的写法
- Python 匹配任意字符(包括换行符)的正则表达式写法
- python -正则表达式--单字符匹配
- Python 匹配任意字符(包括换行符)的正则表达式写法
- python re 正则表达式总结 匹配指定字符
- Python 匹配任意字符(包括换行符)的正则表达式写法
- python正则表达式匹配中文
- Python: 正则表达式匹配多行,实现多行匹配模式
- Python :正则表达式匹配
- 匹配中文字符的正则表达式
- 正则表达式之 Unicode 匹配特殊字符
- 鱼c笔记——Python正则表达式(一):匹配IP地址
- C#正则表达式匹配被双引号包起来的中文并返回匹配的结果
- 正则表达式 匹配特殊字符
- 用python3.x正则表达式匹配中文字符串
- [正则表达式] 能匹配出多行注释之外的所有空白字符的正则表达式:)