python中re的安装步骤_python 中re模块的re.compile()方法

一、re.compile()简介

re.compile()是用来优化正则的,它将正则表达式转化为对象,re.search(pattern, string)的调用方式就转换为 pattern.search(string)的调用方式,多次调用一个正则表达式就重复利用这个正则对象,可以实现更有效率的匹配

re.compile()语法格式如下:

compile(pattern[,flags] )

通过python的help函数查看compile含义:

compile(pattern, flags=0)

pattern : 一个字符串形式的正则表达式

flags : 可选,表示匹配模式,比如忽略大小写,多行模式等,具体参数为:

1).re.I(re.IGNORECASE): 忽略大小写2).re.M(MULTILINE): 多行模式,改变'^'和'$'的行为3).re.S(DOTALL): 点任意匹配模式,改变'.'的行为4).re.L(LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定5).re.U(UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性6).re.X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释

举例:正则表达式为三个”号引起来的多行字符串,则将匹配模式设置为re.X 可以多行匹配

pattern1 = re.compile(r”“”\d + #整数部分

. #小数点

\d * #小数部分”“”, re.X)

二、使用

re.compile()生成的是正则对象,单独使用没有任何意义,需要和findall(), search(), match()搭配使用

2.1 结合findall(),返回一个列表

importre

content= 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'reg= re.compile('\w*o\w*')

x=reg.findall(content)print(x) #['Hello', 'from', 'Chongqing', 'montain', 'to', 'you']

2.1 结合match()

importre

reg= re.compile(r'^@.*? RPA\[([0-9a-f]+)\]')

msg= '@www.pu RPA[7886481]: 收到录单任务,手机:1580vvvv18950。任务处理中,请稍候。'mtch=reg.match(msg)print(mtch) #

print(mtch.group()) #@www.pu RPA[7886481]

print(mtch.group(1)) #7886481 # 分组内内容

print(mtch.start(1)) #12

print(mtch.end(1)) #19

print(mtch.span(1)) #(12, 19) # 分组内的元素范围

print(mtch.span()) #(0, 20)

2.2 结合search()

importre

content= 'Hell, 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(z.group()) #from

print(z.span()) #(18, 22)

三、cpython对re.compile()的优化

虽然re.compile()好处很多,但是在cpython中其实你用不用都无所谓,因为cpython内部已经兼容了re.compile(),可以点进findall(), search(), match()的源码:

1652510-20200923190810587-656044021.png

你再看看re.compile()的:

def compile(pattern, flags=0):"Compile a regular expression pattern, returning a Pattern object."

return _compile(pattern, flags)

我们常用的正则表达式方法,都已经自带了compile了!

根本没有必要多此一举先re.compile再调用正则表达式方法

当然,可以选择用也可以不用,遇到别人写的要知道怎么回事,换了语言后就需要用re.compile了,用还是不用的更多讨论见链接以及讨论区

参考:

https://blog.csdn.net/Darkman_EX/article/details/80973656

https://www.jb51.net/article/126754.htm

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值