正则表达式re.compile()的使用
使用正式用语,避免口语化表达。 #生活技巧# #职场生存技巧# #公文格式规范#
re 模块提供了不少有用的函数,用以匹配字符串,比如:
compile 函数match 函数search 函数findall 函数finditer 函数split 函数sub 函数subn 函数re 模块的一般使用步骤如下:
使用 compile 函数将正则表达式的字符串形式编译为一个 Pattern 对象通过 Pattern 对象提供的一系列方法对文本进行匹配查找,获得匹配结果(一个 Match 对象)最后使用 Match 对象提供的属性和方法获得信息,根据需要进行其他的操作compile 函数
compile 函数用于编译正则表达式,生成一个 Pattern 对象,它的一般使用形式如下:
re.compile(pattern[, flag])
python
运行
其中,pattern 是一个字符串形式的正则表达式,flag 是一个可选参数,表示匹配模式,比如忽略大小写,多行模式等。
下面,让我们看看例子。
import re
pattern = re.compile(r'\d+')
python
运行
在上面,我们已将一个正则表达式编译成 Pattern 对象,接下来,我们就可以利用 pattern 的一系列方法对文本进行匹配查找了。Pattern 对象的一些常用方法主要有:
match 方法search 方法findall 方法finditer 方法split 方法sub 方法subn 方法正则表达式re.compile()
compile()的定义:
compile(pattern, flags=0)
Compile a regular expression pattern, returning a pattern object.
python
运行
从compile()函数的定义中,可以看出返回的是一个匹配对象,它单独使用就没有任何意义,需要和findall(), search(), match()搭配使用。
compile()与findall()一起使用,返回一个列表。
import re
def main():
content = 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'
regex = re.compile('\w*o\w*')
x = regex.findall(content)
print(x)
if __name__ == '__main__':
main()
python
运行
compile()与match()一起使用,可返回一个class、str、tuple。但是一定需要注意match(),从位置0开始匹配,匹配不到会返回None,返回None的时候就没有span/group属性了,并且与group使用,返回一个单词‘Hello’后匹配就会结束。
import re
def main():
content = 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'
regex = re.compile('\w*o\w*')
y = regex.match(content)
print(y)
print(type(y))
print(y.group())
print(y.span())
if __name__ == '__main__':
main()
python
运行
compile()与search()搭配使用, 返回的类型与match()差不多, 但是不同的是search(), 可以不从位置0开始匹配。但是匹配一个单词之后,匹配和match()一样,匹配就会结束。
import re
def main():
content = 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'
regex = re.compile('\w*o\w*')
z = regex.search(content)
print(z)
print(type(z))
print(z.group())
print(z.span())
if __name__ == '__main__':
main()
python
运行
网址:正则表达式re.compile()的使用 https://www.yuejiaxmz.com/news/view/1438121
相关内容
文本清洗正则表达式(持续更新)python 中re模块的re.compile()方法
揭秘正则验证:轻松掌握不包含关键字的技巧,让数据清洗更高效!
解码生活难题:正则表达式,你的数据整理神器
掌握Tasker正则表达式,轻松实现智能任务自动化
揭秘正则表达式:超市购物清单的“家属版”高效管理术
Python 正则表达式 flags 参数
解锁拖把命名新潮流:轻松掌握拖把更名器的正则表达式技巧!
揭秘SQL正则表达式的中文替换技巧:轻松实现高效数据清洗与转换
揭秘:轻松掌握最新银行卡号正则表达式,安全防范攻略大公开!

