compile 函数用于编译正则表达式,返回一个正则表达式对象,供 match()、search() 、findall()等函数使用。
格式:re.compile(正则表达式【, 标志位】)
import re
a ='a1b2c3d4e5f6'
pattern = re.compile('\d') # 匹配数字
s = pattern.match(a) # 查找头部,没有匹配
print(s)
s = pattern.match(a,1,10) # 查找从索引 1 开始10结束
print(s) # 返回一个 Match 对象

import re
a ='a1b2c3d4e5f6'
pattern = re.compile('\d') # 匹配数字
s = pattern.findall(a) # 查找头部,没有匹配
print(s) # 返回一个列表
s = pattern.findall(a,5,10) # 查找从索引 5 开始10结束
print(s)

本文介绍了Python中如何使用re模块的compile函数编译正则表达式,创建正则表达式对象,并通过该对象调用match(), search(), findall()等方法进行字符串匹配与搜索。文章通过具体示例展示了如何定位特定字符或模式。
1045

被折叠的 条评论
为什么被折叠?



