正则表达式在python中的使用

常用函数

re.compile()

compile()的定义:compile(pattern, flags=0)

Compile a regular expression pattern, returning a pattern object.

从compile()函数的定义中,可以看出返回的是一个匹配对象,它单独使用就没有任何意义,需要和findall(), search(), 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*')
x = regex.findall(content)
print(x)


if __name__ == '__main__':
main()
# ['Hello', 'from', 'Chongqing', 'montain', 'to', 'you']


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

 

 
posted @ 2020-07-14 14:52  沉默的云  阅读(159)  评论(0)    收藏  举报