python 中re模塊的re.compile()方法


一、re.compile()簡介

re模塊中有re.match、re.serch、re.findall,也是最常用的,詳細用法見鏈接

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(),返回一個列表

import re

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()

import re

reg = re.compile(r'^@.*? RPA\[([0-9a-f]+)\]')
msg = '@www.pu RPA[7886481]: 收到錄單任務,手機:1580vvvv18950。任務處理中,請稍候。'
mtch = reg.match(msg)
print(mtch)  # <re.Match object; span=(0, 20), match='@www.pu RPA[7886481]'>
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()

import re

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)  # <re.Match object; span=(18, 22), match='from'>
print(z.group()) # from
print(z.span())  #(18, 22)

三、cpython對re.compile()的優化

雖然re.compile()好處很多,但是在cpython中其實你用不用都無所謂,因為cpython內部已經兼容了re.compile(),可以點進findall(), search(), match()的源碼:

 

 你再看看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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM