Python的正則表達式
Python中使用re模塊提供了正則表達式處理的能力
常量
使用 | 位或 運算開啟多種選項
方法
import re
編譯
re.compile(pattern, flags=0)
設定flags、編譯模式,返回正則表達式對象 regex。
pettern就是正則表達式字符串,flags是選項,正則表達式需要被編譯,為了提高效率,這些寫編譯后的結果被保存,下次使用同的pattern的時候,就不需要再次版編譯
re的其它方法為了提高效率都調用了編譯方法,就是為了提速
單次匹配
re.match(pattern,string,flags=0)
regex.match(string [,pos [,endpos]])
返回match對象
match匹配從字符串的開頭匹配,regex對象match方法可以重設定個開始位置和結束位置。
re.search(pattern,string,flags=0)
regex.search(string [,pos [,endpos]])
返回match對象
從頭搜索直到第一個匹配,regex對象serch方法可以沖設定開始位置和結束位置。
re.fullmatch(pattern,string,flags=0)
regex.fullmatch(string [,pos [,endpos]])
返回match對象
整個字符串和正則表達式匹配
全文搜索
re.findall(pattren,string,flags=0)
regex.findall(string [, pos [,endpos]])
對整個字符串,從左至右,返回左右匹配項的列表
如果pattern使用組,則列表元素為組的匹配內容,不使用組,則元素為匹配內容
re.findeiter(pattern,striing,flags=0)
regex,finditer(string [,pos [,endpos]])
對整個字符串,從左至右,返回所有匹配項,返回迭代器
注意:迭代出來的元素為match對象
匹配替換
re.sub(pattern,replacement,string,count=0,flags=0)
regex.sub(replacement,string,count=0)
返回new_string
使用pattern 對字符串string 進行匹配,對匹配項使用replacement替換
repalcement可以是string、bytes、function
re.subn(pattern,replacement,string,count=0,flags=0)
regex.subn(replacement,string,count=0)
同re.sub 返回一個元組(new_string , number_of_sub_made)
分割字符串
字符串的分割函數(shù)split , 太難用,不能指定多個字符進行分割
re.split(pattern,string,maxsplit=0,flags=0)
regex.split(string,maxsplit=0)
分組
使用小括號的pattern捕獲的數(shù)據(jù)被放到了組group中。
match、search 函數(shù)可以返回match對象;findall 返回字符串列表;finditer返回一個個match對象
如果pattern中使用了分組,如果有匹配的結果,會在match對象中:
1.使用,group(n)方式返回對應分組,1~N 是對應的分組,0返回整個匹配的字符串
2.如果使用了命名分組沒,可以使用group(“name”)的方式獲取分組
3.也可以使用groups()返回所有分組
4.使用groupdict()返回所有命名的分組
matchaer.group() 返回 字符串
matchaer.group(‘name’) 返回 字符串
matcher.groups() 返回 分組組成的tuple
matcher.groupdict()
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
網(wǎng)頁名稱:Python——正則表達式re模塊-創(chuàng)新互聯(lián)
轉載注明:http://aaarwkj.com/article2/dpesic.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供標簽優(yōu)化、網(wǎng)站內鏈、App設計、靜態(tài)網(wǎng)站、建站公司、ChatGPT
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容