在 《用最简单的方式教会你使用Python正则》一文中, 我们介绍了正则表达式该如何书写, 还通过简单的示例介绍了 Python 中如何通过 re 模块使用正则功能。今天本文将通过以下内容详细介绍 re 模块方法以及相关类的使用。
re.match函数
match 函数是一个常用的匹配方法,但是该方法是从字符串起始位置匹配,如果起始位置匹配失败, 则返回 None,否则返回 Match 对象。(原文注释: Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.)
其中 pattern 可以是正则表达式字符串, 也可以是 Pattern 对象
import re
# 在起始位置匹配
re.match(r"\d+", '123abc')
# 不在起始位置不匹配
re.match(r"\d+", 'abc123')
# <re.Match object; span=(0, 3), match='123'>
# None
re.search函数
该方法用于搜索整个字符串,如果查找到匹配项, 则返回 Match 对象, 如未匹配, 则返回 None, flags用于指定匹配模式
import re
# 在起始位置匹配
print(re.search(r"(?P<num>\d+)", '123abc456def789'))
# 不在起始位置不匹配
print(re.search(r"\d+", 'abc123'))
# <re.Match object; span=(0, 3), match='123'>
# <re.Match object; span=(3, 6), match='123'>
方法 | 相同 | 不同 |
re.match | 参数相同, 返回结果相同,如果匹配则返回第一个匹配项, 无匹配则返回 None | 匹配字符串开始, 符合则返回 |
re.search | 匹配字符串全部内容, 直到查找到匹配项 |
re.split函数
re.split 方法使用和产生的效果与 str.split一致, 其中 re.split 可额外添加 flags 一个参数,用于指定匹配模式
import re
print(re.split(",", "1,2,3,4"))
print("1,2,3,4".split(","))
# ['1', '2', '3', '4']
# ['1', '2', '3', '4']
re.sub/ re.subn 函数
两个函数都是用来替换字符串的, subn 会返回一个元祖, 包含替换后的字符串和替换的次数
# 查找字符串中的数字,并替换为1
print(re.sub(r"\d", "1", "222aaa"))
print(re.subn(r"\d", "1", "222aaa"))
# 111aaa
# ('111aaa', 3)
re.findall/ re.finditer
相同点 | 不同点 | |
re.findall | 在字符串中找到正则表达式所匹配的所有子串 | 返回结果列表 |
re.finditer | 返回包含 Match 对象的迭代器 |
re.findall(r"\d+", "我有200元, 可以吃1条鱼和2瓶啤酒")
# ['200', '1', '2']
for i in re.finditer(r"\d+", "我有200元, 可以吃1条鱼和2瓶啤酒"):
print(i.group())
# 200
# 1
# 2
注意: 当数据量较大时, 建议使用 finditer, 可以更节省内存和高效
re.fullmatch 函数
当给定的正则能全量匹配字符串时, 返回 Match 对象, 否则返回 None。
原文注释: Try to apply the pattern to all of the string, returning a Match object, or None if no match was found.
# \w*可以匹配所有字母, 数字, 下划线,
# 但是不能匹配",", 所以这个不是全匹配
print(re.fullmatch(r"\w*", "我有200元,可以吃1条鱼和2瓶啤酒"))
# None
# \w*可以匹配所有字母, 数字, 下划线, 是全匹配
print(re.fullmatch(r"\w*", "我有200元_可以吃1条鱼和2瓶啤酒"))
# <re.Match object; span=(0, 18), match='我有200元_可以吃1条鱼和2瓶啤酒'>
re.compile 和 re.Pattern 类
通过 re.compile 预编译一个正则表达式,会返回 Pattern 类, Pattern 类中有如下方法和 re 中使用方式相同
match(str, pos, endpos) | 方法参数中: pos 代表字符串起始 index 位置, endpos 代表字符串结束 index 位置 |
search(str, pos, endpos) | |
split(str, maxsplit) | |
sub(repl, str, count)/subn(repl, str, count) | |
findall(str, pos, endpos) | |
finditer(str, pos, endpos) | |
fullmatch(str, pos, endpos) |
re.Match 类
Match 代表匹配对象, Python 在每次匹配成功后都会生成一个 Match 对象,用于获取匹配成功后的内容
import re
# 获取到Match对象
match = re.search(r"(?P<num>\d+)(?P<word>\w+)", '123abc456def789')
# <re.Match object; span=(0, 15), match='123abc456def789'>
print(match.span())
# (0, 15) 获取匹配的范围
print(match.group())
# 获取匹配的内容123abc456def789
print(match.groups())
# 返回匹配的分组元祖 ('123', 'abc456def789')
print(match.groupdict())
# 返回匹配分组的字典 {'num': '123', 'word': 'abc456def789'}
print(match.start(0))
# 获取匹配内容开始的 index 0
print(match.end(0))
# 获取匹配内容结束的 index 15
本文内容参考自Python官网文档