python学习——re库的常用函数

参考资料:python网络爬虫技术与应用【邓维】

1、match()

从字符串头部开始匹配字符。

python 复制代码
import re
content="The123456ismyonephonenumber."
# 字符串长度
print(len(content)) 
# 使用match匹配,第一个参数为正则表达式,第二个参数为要匹配的字符串
result=re.match(r'^The',content)
print(result)
# 输出匹配内容
print(result.group())
# 输出匹配内容的位置索引
print(result.span())

2、search()

与match()方法不同,search()方法不需要从头开始匹配。

python 复制代码
import re
content="OtherThe123456ismyonephonenumber."
result=re.search(r"The.*?(\d+).*?number.",content)
print(result.group())

3、findall()

match()方法和search()方法都是返回匹配到的第一个内容就结束匹配,而findall()方法是返回全部符合匹配规则的内容,返回的是一个列表。

python 复制代码
import re
text="pyypppyyyyypppp"
pattern="py"
for match in re.findall(pattern,text):
    print("Found{!r}".format(match))

4、sub()

去除或替换匹配的字符。假如写sub("\d+","-"),则是把匹配的内容调换成"-",例子如下:

python 复制代码
import re
content='54abc59de335f7778888g'
content=re.sub("\d+","",content)
print(content)
相关推荐
焚 城13 分钟前
UniApp中Flex布局学习
学习·uni-app
你真的可爱呀15 分钟前
uniapp学习【整体实践】
前端·学习·uni-app·实践
CodeCraft Studio19 分钟前
Excel处理控件Aspose.Cells教程:使用 Python 将 HTML 转换为 Excel
python·html·excel·aspose·aspose.cells·html转excel
润 下36 分钟前
C语言——深入解析C语言指针:从基础到实践从入门到精通(二)
c语言·开发语言·经验分享·笔记·学习·程序人生
王中阳Go43 分钟前
Python 的 PyPy 能追上 Go 的性能吗?
后端·python·go
Goboy1 小时前
控制仙术流程 - 抉择与循环的艺术
后端·python
麦麦大数据1 小时前
F024 vue+flask电影知识图谱推荐系统vue+neo4j +python实现
vue.js·python·flask·知识图谱·推荐算法·电影推荐
AI小云1 小时前
【Python与AI基础】Python编程基础:读写CSV文件
人工智能·python
知识分享小能手1 小时前
微信小程序入门学习教程,从入门到精通,电影之家小程序项目知识点详解 (17)
前端·javascript·学习·微信小程序·小程序·前端框架·vue
Goboy1 小时前
Python修仙入门 - 踏入仙门的第一步
后端·python