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)
相关推荐
小李不想当小白4 小时前
WDG看门狗(STM32标准库学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习·嵌入式
木头左4 小时前
【Python】不点浏览器发博客:逆向 CSDN 创作中心接口做 md-publish 技能
python·自动化·api
Tt有了t5 小时前
设计模式速查
java·python·设计模式
deepseek235 小时前
Python日志拖慢请求?QueueHandler排队、丢失与退出实测
python·性能优化·logging·后端开发·queuehandler
用户91294046848425 小时前
Codex 从零到能交付(05):第一次改代码:生成一个文件清单脚本
python
Dmz丶5 小时前
前端转 AI 100 天 Day 38:Token 管理与成本优化——别让 API 账单爆炸
python
用户298698530146 小时前
Python 自动化处理 Word 页眉页脚的几种典型场景
后端·python·api
終不似少年遊*6 小时前
【安全业务Agent】从场景到编排
python·react.js·ai·langchain·agent·安全架构·工作流
AKA__Zas7 小时前
接口自动化测试(1.0 初认识
python·ci/cd·学习方法
用户0332126663677 小时前
使用 Python 在 Excel 文档中添加水印
python·excel