正则表达式
- 用正则表达式查找文本模式
import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d\-\d\d\d\d') mo = phoneNumRegex.search('My number is 415-555-4242.') print(mo.group())
用import re 导入正则表达式模块;
用re.compile()函数创建一个Regex对象;
向Regex对象的search()方法传入想查找的字符串。它返回一个Match对象;
调用Match对象的group()方法,返回实际匹配文本的字符串。
- 用正则表达式匹配更多模式
- 利用括号分组
phoneNumReg = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') mo1 = phoneNumReg.search('My number is 415-555-4222.') print(mo1.group(1)) print(mo1.group(2)) print(mo1.group(0)) print(mo1.groups())
415
555-4222
415-555-4222
('415', '555-4222')
-
- 用管道匹配多个分组
heroRegex = re.compile(r'Batman|Tina Fey') mo1 = heroRegex.search("Batman and Tina Fey.") print(mo1.group()) batRegex = re.compile(r'Bat(man|mobile|copter|bat)') mo = batRegex.search("Batmobile lost a wheel") print(mo.group()) print(mo.group(1))
-
- 用问号实现可选匹配
# 用问号实现可选匹配(匹配这个问号之前的分组零次或一次) batRegex = re.compile(r'Bat(wo)?man') mo1 = batRegex.search("The Adventures of Batman") print(mo1.group()) mo2 = batRegex.search("The Adventures of Batwoman") print(mo2.group()) phoneRegex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d') mo1 = phoneRegex.search("My number is 415-555-4242") print(mo1.group()) mo2 = phoneRegex.search("My number is 555-4242") print(mo2.group())
-
- 用星号匹配0次或多次
batRegex = re.compile(r"Bat(wo)*man") mo1 = batRegex.search("The Adventures of Batman") print(mo1.group()) mo2 = batRegex.search("The Adventures of Batwoman") print(mo2.group()) mo3 = batRegex.search("The Adventures of Batwowowowoman") print(mo3.group())
-
- 用加号匹配一次或多次
batRegex = re.compile(r"Bat(wo)+man") mo1 = batRegex.search("The Adventures of Batwoman") print(mo1.group()) mo2 = batRegex.search("The Adventures of Batwowowowoman") print(mo2.group()) mo3 = batRegex.search("The Adventures of Batman") print(mo3==None)
-
- 用花括号匹配特定次数
haRegex = re.compile(r'(Ha){3}') mo1 = haRegex.search("HaHaHa") print(mo1.group()) mo2 = haRegex.search("Ha") print(mo2==None)
作者:solomon-zj
出处:https://www.cnblogs.com/solomon-zj/p/17382728.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
愚者不努力,懒人盼巅峰
Buy me a cup of coffee ☕.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现