打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
正则表达式re.compile()的使用

正则表达式re.compile()

compile()的定义:

compile(pattern, flags=0) Compile a regular expression pattern, returning a pattern object.

从compile()函数的定义中,可以看出返回的是一个匹配对象,它单独使用就没有任何意义,需要和findall(), search(), match()搭配使用。
compile()与findall()一起使用,返回一个列表。

import redef 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()# ['Hello', 'from', 'Chongqing', 'montain', 'to', 'you']

compile()与match()一起使用,可返回一个class、str、tuple。但是一定需要注意match(),从位置0开始匹配,匹配不到会返回None,返回None的时候就没有span/group属性了,并且与group使用,返回一个单词‘Hello’后匹配就会结束。

import redef 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()# <_sre.SRE_Match object; span=(0, 5), match='Hello'># <class '_sre.SRE_Match'># Hello# (0, 5)

compile()与search()搭配使用, 返回的类型与match()差不多, 但是不同的是search(), 可以不从位置0开始匹配。但是匹配一个单词之后,匹配和match()一样,匹配就会结束。

import redef 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()# <_sre.SRE_Match object; span=(0, 5), match='Hello'># <class '_sre.SRE_Match'># Hello# (0, 5)
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Python3 如何优雅地使用正则表达式(详解二)
Python Re 模块
[Python爬虫] 五、数据提取之正则表达式re模块
[小小明]Python正则表达式速查表与实操手册
python正则表达式
python中的正则表达式(re模块)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服