码迷,mamicode.com
首页 > 其他好文 > 详细

re.compile()

时间:2020-06-19 15:39:23      阅读:40      评论:0      收藏:0      [点我收藏+]

标签:one   mat   obj   使用   col   arch   mpi   pil   组成   

1、定义

compile(pattern, flags=0) 

**   正则匹配规则: \w*o\w*

\w* 表示匹配由大小写英文字bai母数字和下划线组成的0个或多个du字符
o 表示匹zhi配字符o
\w*o\w* 表示匹配含有o的字dao符串(不管o在首字母还是在尾字母还是在中间)

 

2、与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()
# [Hello, from, Chongqing, montain, to, you]

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

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

 

re.compile()

标签:one   mat   obj   使用   col   arch   mpi   pil   组成   

原文地址:https://www.cnblogs.com/CXMS/p/13163174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!