1. 程式人生 > 實用技巧 >Python 正則表達的幾種方法

Python 正則表達的幾種方法

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯絡我們以作處理

以下文章來源於騰訊雲,作者:資料醫生

( 想要學習Python?Python學習交流群:1039649593,滿足你的需求,資料都已經上傳群檔案流,可以自行下載!還有海量最新2020python學習資料。 )

Python 使用re 模組提供了正則表示式處理的能力

re.M                         多行模式
re.MULTILNE
re.S                         單行模式
re.DOTALL      
re.I                         忽略大小寫
re.IGNORECASE
re.X                         忽略表示式中的空白字元
re.VERBOSE
使用 
| 位 或 / 運算開啟多種選項

方法

編譯

re.compile(patten,flags=0)

設定flags, 編譯模式,返回正則表示式物件regex。

pattern 就是正則表示式字串,flags是選項。正則表達需要被編譯,為了提高提高效率,這些編譯後的結果被儲存,下次使用同樣的pattern 的時候,就不需要再次編譯。

re的其他方法為了提高效率都呼叫了編譯方法,就是為了提速。

單次匹配
re.march(pattern,string,flags=0)
regex.match(string[,pos[,endpos]])
match匹配從字串開頭匹配,regex物件match 方法可以重設定開始位置和結束位置。返回match物件

re.search(pattern,string,flags=0)
regex.search(string[,pos[,endpod]])
從頭搜尋直到第一個匹配,regex物件search方法可以重設定開始位置和結束位置,返回match物件

re.fullmatch(pattern,string,flags=0)
regex.fullmatch(string[,pos[,endpos]])
整個字串和正則表示式匹配

全文搜尋
re.findall(pattern,string,flags=0)
regex.findall(string[,pos[,endpos]])
對整個字串,從左到右匹配,返回所有匹配的列表

re.finditer(pattern,string,flags=0)
redex.finditer(string[,pos[,endpos]])
對整個字串,從左到右匹配,返回所有匹配項,返回迭代器。注意每次迭代返回的是match物件

匹配替換

re.sub(pattern,replacement,string,count=0,flags=0)
regex.sub(reglacement,string,count=0)
使用pattern對字串string 進行匹配,對匹配項使用repl替換。
replacement可以是string, bytes, function.

re.subn(pattern,replacement,string,count=0,flags=0)
regex.subn(replacement,string,count=0)
同sub返回一個元組(new_string,number_of_subs_made)

字串分割
字串的分割函式,太難用,不能指定多個字元進行分割。
re.split(pattern,string,maxsplit=0,flags=0)
re.split分隔字串

分組
使用小括號的pattern 捕獲的資料被放到了組group 中。
match ,search 函式可以返回match 物件;findall 返回字串列表;finditer 返回一個個match 物件

如果pattern 中使用哦分組,如果有匹配的結果,會在match 物件中
1、使用group(N)方式返回對應分組,1-N 是對應的分組,0返回整個匹配的字串
2、如果使用了命名分組,可以使用group('name') 的方式取分組
3、也可以使用groups()返回多有分組
4、使用groupdict()返回所有命名的分組