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)
相关推荐
火白学安全18 分钟前
《Python红队攻防零基础脚本编写:进阶篇(一)》
开发语言·python·安全·web安全·网络安全·系统安全
FreeCode28 分钟前
LangGraph1.0智能体开发:运行时系统
python·langchain·agent
青瓷程序设计40 分钟前
植物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
习习.y1 小时前
关于python中的面向对象
开发语言·python
lingggggaaaa1 小时前
免杀对抗——C2远控篇&PowerShell&有无文件落地&C#参数调用&绕AMSI&ETW&去混淆特征
c语言·开发语言·笔记·学习·安全·microsoft·c#
hmbbcsm1 小时前
练习python题目小记(六)
开发语言·python
wow_DG1 小时前
【Python✨】VS Code 秒开 Python 类型检查:一招 mypy + settings.json 让你的 Bug 原地现形!
python·json·bug
Aspect of twilight2 小时前
LeetCode华为大模型岗刷题
python·leetcode·华为·力扣·算法题
空影星2 小时前
高效追踪电脑使用时间,Tockler助你优化时间管理
python·django·flask
LiLiYuan.2 小时前
【Lombok库常用注解】
java·开发语言·python