博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python正则表达式返回首次匹配到的字符及查询的健壮性
阅读量:7261 次
发布时间:2019-06-29

本文共 912 字,大约阅读时间需要 3 分钟。

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 "", line 1, in 
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 "", line 1, in 
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

你可能感兴趣的文章
Promise面试题2实现异步串行执行
查看>>
Python使用xslt提取网页数据
查看>>
git常用命令速查表
查看>>
神经网络基础
查看>>
Linux常用命令
查看>>
k8s与aws--如何在cloud-provider=aws的k8s中设置externalTrafficPolicy为local
查看>>
koa2系列教程:综合koa2搭建登录注册页面
查看>>
区块链技术到底能解决什么问题?
查看>>
“价值2个亿”的AI代码
查看>>
ANGULAR JS 常用指令NG-IF、NG-CLASS、NG-OPTION、NG-VALUE、NG-CLICK是如何使用的?
查看>>
搞懂 JavsScript 异步 —  事件轮询
查看>>
(一)线程的发展历史
查看>>
为NEO-GUI 添加插件系统
查看>>
TBSSQL 的那些事 | TiDB Hackathon 2018 优秀项目分享
查看>>
手机秒变IoT设备?——巧妙利用阿里云物联网平台
查看>>
使用truffle开发以太坊Dapp
查看>>
【Leetcode刷题】第 35 题:Search Insert Position 搜索插入位置——解题篇
查看>>
AliOS Things 声源定位应用演示
查看>>
揭开React中server-side rending的神秘面纱
查看>>
《JavaScript高级程序设计》读书笔记
查看>>