Python3中正则模块re.compile、re.match及re.search函数用法详解

青禾
青禾
发布时间:2026-10-13 | 5人浏览过
原创

本文详细解析Python3中re模块的核心函数。介绍re.compile编译正则对象以提升效率,详解re.match从字符串开头匹配及re.search全局搜索的区别。涵盖flags标志位用法、分组匹配属性及实际代码示例,帮助开发者掌握正则处理技巧。

本文通过具体实例,深入讲解Python3中正则表达式模块re下的compile、match以及search函数的使用方法,旨在为读者提供实用的参考指南。

重点解析re模块中的compile、match与search三个核心函数。

参考re模块的官方说明文档以获取更详尽的技术规范。

在编写正则表达式时,字符串前缀使用r表示原生字符串(raw string),其作用是声明字符串内的特殊字符无需进行额外的转义处理。

例如,若要表示换行符\n,可以直接写为r'\n',或者在不使用原生字符串前缀的情况下写为'\n'。

建议在实际开发中优先使用re.match函数进行匹配操作。

关于re.compile()函数的详细说明。

该函数用于编译正则表达式模式,并返回一个编译后的对象。将常用的正则表达式预先编译为正则对象,不仅便于后续多次调用,还能显著提高程序运行效率。

re.compile(pattern, flags=0)

  • 参数pattern用于指定编译时所使用的表达式字符串。
  • 参数flags为编译标志位,用于调整正则表达式的匹配行为。例如,支持同时使用re.L和re.M标志进行匹配。

以下是flags标志位参数的具体说明。

re.I(即re.IGNORECASE):启用此标志后,匹配过程将忽略字母的大小写。

re.L(即re.LOCAL):启用本地化识别(locale-aware)匹配,依据当前环境设置进行匹配。

re.M(即re.MULTILINE):启用多行匹配模式,这将影响锚点^和$的行为,使其分别匹配行的开始和结束。

re.S(即re.DOTALL):启用此标志后,通配符.将匹配包括换行符在内的所有字符。

re.U(即re.UNICODE):根据Unicode字符集解析字符。该标志会影响\w、\W、\b和\B的匹配行为。

re.X(即re.VERBOSE):启用此标志允许在正则表达式中使用更灵活的格式,例如添加注释和空格,从而使正则表达式更易读和理解。

以下是具体的代码示例。

import re
content = 'Citizen wang , always fall in love with neighbour,WANG'
rr = re.compile(r'wan\w', re.I) # 不区分大小写
print(type(rr))
a = rr.findall(content)
print(type(a))
print(a)

findall方法返回的结果是一个list列表对象。

输出类型显示为<class '_sre.SRE_Pattern'>和<class 'list'>,匹配到的内容为['wang', 'WANG']。

关于re.match()函数的详细说明。

re.match函数始终尝试从字符串的起始位置进行匹配,若匹配成功,则返回一个表示匹配结果的match对象,其类型为<class '_sre.SRE_Match'>。

re.match(pattern, string[, flags=0])

  • 参数pattern指代匹配模式,通常由re.compile函数生成的对象提供。
  • 参数string指代需要进行匹配的原始字符串。
import re
pattern = re.compile(r'hello')
a = re.match(pattern, 'hello world')
b = re.match(pattern, 'world hello')
c = re.match(pattern, 'hell')
d = re.match(pattern, 'hello ')
if a:
  print(a.group())
else:
  print('a 失败')
if b:
  print(b.group())
else:
  print('b 失败')
if c:
  print(c.group())
else:
  print('c 失败')
if d:
  print(d.group())
else:
  print('d 失败')

测试结果显示:变量a匹配成功输出hello;变量b因字符串以world开头匹配失败;变量c因长度不足匹配失败;变量d匹配成功输出hello。

以下是match对象所提供的方法和属性列表。

相关参考链接供进一步查阅。

import re
str = 'hello world! hello python'
pattern = re.compile(r'(?P<first>hell\w)(?P<symbol>\s)(?P<last>.*ld!)') # 分组,0 组是整个 hello world!, 1组 hello,2组 ld!
match = re.match(pattern, str)
print('group 0:', match.group(0)) # 匹配 0 组,整个字符串
print('group 1:', match.group(1)) # 匹配第一组,hello
print('group 2:', match.group(2)) # 匹配第二组,空格
print('group 3:', match.group(3)) # 匹配第三组,ld!
print('groups:', match.groups())  # groups 方法,返回一个包含所有分组匹配的元组
print('start 0:', match.start(0), 'end 0:', match.end(0)) # 整个匹配开始和结束的索引值
print('start 1:', match.start(1), 'end 1:', match.end(1)) # 第一组开始和结束的索引值
print('start 2:', match.start(1), 'end 2:', match.end(2)) # 第二组开始和结束的索引值
print('pos 开始于:', match.pos)
print('endpos 结束于:', match.endpos) # string 的长度
print('lastgroup 最后一个被捕获的分组的名字:', match.lastgroup)
print('lastindex 最后一个分组在文本中的索引:', match.lastindex)
print('string 匹配时候使用的文本:', match.string)
print('re 匹配时候使用的 Pattern 对象:', match.re)
print('span 返回分组匹配的 index (start(group),end(group)):', match.span(2))

以下是代码执行后的返回结果详情。

group 0: hello world! group 1: hello group 2: group 3: world! groups: ('hello', ' ', 'world!') start 0: 0 end 0: 12 start 1: 0 end 1: 5 start 2: 0 end 2: 6 pos 开始于: 0 endpos 结束于: 25 lastgroup 最后一个被捕获的分组的名字: last lastindex 最后一个分组在文本中的索引: 3 string 匹配时候使用的文本: hello world! hello python re 匹配时候使用的 Pattern 对象: re.compile('(?P<first>hell\\w)(?P<symbol>\\s)(?P<last>.*ld!)') span 返回分组匹配的 index (start(group),end(group)): (5, 6)

关于re.search函数的详细说明。

re.search函数会对整个字符串进行搜索匹配,并返回第一个匹配成功的字符串对应的match对象。

re.search(pattern, string[, flags=0])

  • 参数pattern指代匹配模式,通常由re.compile函数生成的对象提供。
  • 参数string指代需要进行匹配的原始字符串。
import re
str = 'say hello world! hello python'
pattern = re.compile(r'(?P<first>hell\w)(?P<symbol>\s)(?P<last>.*ld!)') # 分组,0 组是整个 hello world!, 1组 hello,2组 ld!
search = re.search(pattern, str)
print('group 0:', search.group(0)) # 匹配 0 组,整个字符串
print('group 1:', search.group(1)) # 匹配第一组,hello
print('group 2:', search.group(2)) # 匹配第二组,空格
print('group 3:', search.group(3)) # 匹配第三组,ld!
print('groups:', search.groups())  # groups 方法,返回一个包含所有分组匹配的元组
print('start 0:', search.start(0), 'end 0:', search.end(0)) # 整个匹配开始和结束的索引值
print('start 1:', search.start(1), 'end 1:', search.end(1)) # 第一组开始和结束的索引值
print('start 2:', search.start(1), 'end 2:', search.end(2)) # 第二组开始和结束的索引值
print('pos 开始于:', search.pos)
print('endpos 结束于:', search.endpos) # string 的长度
print('lastgroup 最后一个被捕获的分组的名字:', search.lastgroup)
print('lastindex 最后一个分组在文本中的索引:', search.lastindex)
print('string 匹配时候使用的文本:', search.string)
print('re 匹配时候使用的 Pattern 对象:', search.re)
print('span 返回分组匹配的 index (start(group),end(group)):', search.span(2))

需注意re.search与re.match在处理字符串str时的区别,前者搜索整个字符串,后者仅从开头匹配。

以下是相关代码的打印输出结果。

group 0: hello world! group 1: hello group 2: group 3: world! groups: ('hello', ' ', 'world!') start 0: 4 end 0: 16 start 1: 4 end 1: 9 start 2: 4 end 2: 10 pos 开始于: 0 endpos 结束于: 29 lastgroup 最后一个被捕获的分组的名字: last lastindex 最后一个分组在文本中的索引: 3 string 匹配时候使用的文本: say hello world! hello python re 匹配时候使用的 Pattern 对象: re.compile('(?P<first>hell\\w)(?P<symbol>\\s)(?P<last>.*ld!)') span 返回分组匹配的 index (start(group),end(group)): (9, 10)

补充说明:此处提供两款便捷的正则表达式在线工具供读者参考使用。

JavaScript正则表达式在线测试工具的地址为: http://tools.jb51.net/regex/javascript

正则表达式在线生成工具的地址为: http://tools.jb51.net/regex/create_reg

如需了解更多Python相关内容,建议查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》。

希望本文所述内容能对各位Python程序设计师有所帮助。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表