日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Python:正则表达式re.compile()

發布時間:2023/12/20 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python:正则表达式re.compile() 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

正則表達式re.compile()

對于一些經常要用到的正則表達式,可以使用compile進行編譯,后期再使用的時候可以直接拿過來用,執行效率會更快。而且compile還可以指定flag=re.VERBOSE,在寫正則表達式的時候可以做好注釋。
compile()的定義:

compile(pattern, flags=0) Compile a regular expression pattern, returning a pattern object. text = "the number is 20.50" r = re.compile(r"""\d+ # 小數點前面的數字\.? # 小數點\d* # 小數點后面的數字""",re.VERBOSE) ret = re.search(r,text) print(ret.group())

從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() ''' <re.Match object; span=(0, 5), match='Hello'> <class 're.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() ''' <re.Match object; span=(0, 5), match='Hello'> <class 're.Match'> Hello (0, 5) '''

總結

以上是生活随笔為你收集整理的Python:正则表达式re.compile()的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。