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)
相关推荐
claem几秒前
Mac端 Python脚本创建与理解
开发语言·python·macos
lixzest14 分钟前
目标检测算法应用工程师 面试高频题 + 标准答案
python·yolo·目标检测·计算机视觉
mango_mangojuice14 分钟前
C++ 学习笔记(string类)
开发语言·c++·笔记·学习
癫狂的兔子25 分钟前
【BUG】【Python】【Spider】Compound class names are not allowed.
开发语言·python·bug
望忆27 分钟前
关于《Contrastive Collaborative Filtering for Cold-Start Item Recommendation》的学习
学习
jtymyxmz37 分钟前
《Maya2024超级学习手册》3.4.10 实例:制作瓶子模型
学习
木头左43 分钟前
基于Backtrader框架的指数期权备兑策略实现与验证
python
小白郭莫搞科技1 小时前
鸿蒙跨端框架Flutter学习:CurvedAnimation曲线动画详解
学习·flutter·harmonyos
李松桃1 小时前
python第三次作业
java·前端·python