正则表达式
Re模块
匹配查找方法
re.match(表达式,字符串)
:从字符串的起始位置开始匹配正则表达式,如果匹配成功,则返回一个匹配对象;否则返回None
。
1 import re
2 pattern = r'hello'
3 string = 'hello world'
4 match = re.match(pattern, string)
5 if match:
6 print(match.group())#hello
group()用来返回对象的子符串
# 示例 3:使用分组捕获信息 text = "2024-10-01" pattern = r'(\d{4})-(\d{2})-(\d{2})' match = re.search(pattern, text) if match: year = match.group(1) month = match.group(2) day = match.group(3) print(f"Year: {year}, Month: {month}, Day: {day}") # 输出: Year: 2024, Month: 10, Day: 01
re.search()
:在字符串中搜索匹配正则表达式的第一个位置,如果找到匹配,则返回一个匹配对象;否则返回None
。它会扫描整个字符串,而不仅仅是从起始位置开始。
pattern = r'world' string = 'hello world' match = re.search(pattern, string) if match: print(match.group())#world
re.findall()
:在字符串中找到所有匹配正则表达式的子串,并以列表形式返回。如果没有找到匹配项,则返回一个空列表。
pattern = r'\d' string = 'hello world123456789' match = re.findall(pattern, string) print(match)#['1', '2', '3', '4', '5', '6', '7', '8', '9']
re.finditer()
:与re.findall()
类似,但它返回的是一个迭代器,其中每个元素都是一个匹配对象,通过迭代可以逐个获取匹配的子串及其相关信息。
re.sub()
:用于在字符串中替换匹配正则表达式的子串。它接受三个参数:正则表达式模式、替换的字符串、要处理的原始字符串,还可以指定替换的次数。
pattern = r'\d+' replacement = 'X' string = 'abc123def456ghi' new_string = re.sub(pattern, replacement, string) print(new_string)
re.split()
:根据匹配正则表达式的子串来分割字符串,返回分割后的字符串列表。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架