5分鐘速覽python正則表達(dá)式常用函數(shù)
大家好,歡迎來(lái)到 Crossin的編程教室 !
正則表達(dá)式是處理字符串類型的"核武器",不僅速度快,而且功能強(qiáng)大。本文不過(guò)多展開(kāi)正則表達(dá)式相關(guān)語(yǔ)法,僅簡(jiǎn)要介紹python中正則表達(dá)式常用函數(shù)及其使用方法,以作快速查詢?yōu)g覽。
Re模塊是python的內(nèi)置模塊,提供了正則表達(dá)式在python中的所有用法,默認(rèn)安裝位置在python根目錄下的Lib文件夾(如 ..\Python\Python37\Lib)。主要提供了3大類字符串操作方法:
字符查找/匹配
字符替換
字符分割
由于是面向字符串類型的模塊,就不得不提到字符串編碼類型。re模塊中,模式串和搜索串既可以是 Unicode 字符串(常用str類型),也可以是8位字節(jié)串 (bytes,2位16進(jìn)制數(shù)字,例如\xe5), 但要求二者必須是同類型字符串。
預(yù)編譯:compile
import re
pattern = re.compile(r'[a-z]{2,5}')
type(pattern) #re.Pattern
此例創(chuàng)建了一個(gè)正則表達(dá)式式對(duì)象(re.pattern),命名為pattern,用于匹配2-5位小寫(xiě)字母的模式串。后續(xù)在使用其他正則表達(dá)式函數(shù)時(shí),即可使用pattern進(jìn)行方法調(diào)用。
匹配:match
import re
pattern = re.compile(r'[a-z]{2,5}')
text1 = 'this is a re test'
res = pattern.match(text1)
print(res) #<re.Match object; span=(0, 4), match='this'>
if res:
print(res.group()) #this
print(res.span()) #(0, 4)
text2 = '是的, this is a re test'
print(pattern.match(text2))#None
match函數(shù)還有一個(gè)變形函數(shù)fullmatch,當(dāng)且僅當(dāng)模式串與文本串剛好全部匹配時(shí),返回一個(gè)匹配對(duì)象,否則返回None
搜索:search
import re
pattern = re.compile(r'\s[a-z]{2}')
text1 = 'this is a re test'
res = pattern.search(text1)
print(res) #<re.Match object; span=(4, 7), match=' is'>
if res:
print(res.group()) #is
print(res.span()) #(4, 7)
pattern2 = re.compile(r'\s[a-z]{5}')
text2 = '是的,this is a re test'
print(pattern2.search(text2))#None
全搜索:findall/finditer
import re
pattern = re.compile(r'\s[a-z]{2,5}')
text1 = 'this is a re test'
res = pattern.findall(text1)
print(res) #[' is', ' re', ' test']
import re
pattern = re.compile(r'\s[a-z]{2,5}')
text1 = 'this is a re test'
res = pattern.finditer(text1)
for r in res:
print(r.group())
"""
is
re
test
"""
import re
pattern = re.compile(r'\d{2,5}')
text = 'this is re test'
re.findall('[a-z]+', text) #['this', 'is', 're', 'test']替換:sub/subn
import re
text = 'today is 2020-03-05'
print(re.sub('-', '', text)) #'today is 20200305'
print(re.sub('-', '', text, 1)) #'today is 202003-05'
print(re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', text)) #'today is 03/05/2020'
import re
text = 'today is 2020-03-05'
print(re.subn('-', '', text)) #('today is 20200305', 2)
分割:split
import re
text = 'today is a re test, what do you mind?'
print(re.split(',', text)) #['today is a re test', ' what do you mind?']
python中的re模塊提供了正則表達(dá)式的常用方法,每種方法都包括類方法調(diào)用(如re.match)或模式串的實(shí)例調(diào)用(pattern.match)2種形式
常用的匹配函數(shù):match/fullmatch
常用的搜索函數(shù):search/findall/finditer
常用的替換函數(shù):sub/subn
常用的切割函數(shù):split
還有其他很多方法,但不是很常用,具體可參考官方文檔
另外,python還有第三方正則表達(dá)式庫(kù)regex可供選擇
如果文章對(duì)你有幫助,歡迎轉(zhuǎn)發(fā)/點(diǎn)贊/收藏~
_往期文章推薦_
