python正則表示式最詳解
阿新 • • 發佈:2021-11-05
目錄
- 一、正則表示式–元字元
- 1. 數量詞
- 2. 字元匹配
- 3. 邊界匹配
- 4. 組
- 5. 匹配模式引數
- 二、方法
- re.findall
- re.match
- group匹配物件
- re.search
- re.compile
- 三、檢索和替換
- re.sub 替換字串
- 總結
一、正則表示式–元字元
re 模組使 語言擁有全部的正則表示式功能
1. 數量詞
# 提取大小寫字母混合的單詞 import re a = 'Excel 12345Word23456PPT12Lr' r = re.findall('[a-zA-Z]{3,5}',a) # 提取字母的數量3個到5個 print(r) # ['Excel','Word','PPT'] # 貪婪 與 非貪婪 【Python預設使用貪婪模式】 # 貪婪:'[a-zA-Z]{3,5}' # 非貪婪:'[a-zA-Z]{3,5}?' 或 '[a-zA-Z]{3}' # 建議使用後者,不要使用?號,否則你會與下面的?號混淆 # 匹配0次或無限多次 *號,*號前面的字元出現0次或無限次 import re a = 'exce0excell3excel3' r = re.findall('excel*',a) r = re.findall('excel.*',a) # ['excell3excel3'] # excel 沒有l 有很多l都可以匹配出來 print(r) # ['exce','excell','excel'] # 匹配1次或者無限多次 +號,+號前面的字元至少出現1次 import re a = 'exce0excell3excel3' r = re.findall('excel+',a) print(r) # ['excell','excel'] # 匹配0次或1次 ?號,?號經常用來去重複 import re a = 'exce0excell3excel3' r = re.findall('excel?',a) print(r) # ['exce','excel','excel']
2. 字元匹配
line = 'xyz,xcz.xfc.xdz,xaz,xez,xec' r = re.findall('x[de]z',line) # pattern 是x開始,z結束,含d或e print(r) # ['xdz','xez'] r = re.findall('x[^de]z',line) # pattern 是x開始,z結束,不是含d或e print(r) # ['xyz','xcz','xaz']
# \w 可以提取中文,英文,數字和下劃線,不能提取特殊字元 import re a = 'Excel 12345Word\n23456_PPT12lr' r = re.findall('\w',a) print(r) # ['E','x','c','e','l','1','2','3','4','5','W','o','r','d','6','_','P','T','r'] # \W 提取特殊字元,空格 \n \t import re a = 'Excel 12345Word\n23456_PPT12lr' r = re.findall('\W',a) print(r) # [' ','\n']
3. 邊界匹配
# 限制電話號碼的位置必需是8-11位才能提取 import re tel = '13811115888' r = re.findall('^\d{8,11}$',tel) print(r) # ['13811115888']
4. 組
# 將abc打成一個組,{2}指的是重複幾次,匹配abcabc import re a = 'abcabcabcxyzabcabcxyzabc' r = re.findall('(abc){2}',a) # 與 # ['abc','abc'] print(r) r = re.findall('(abc){3}',a) # ['abc']
5. 匹配模式引數
# findall第三引數 re.I忽略大小寫 import re a = 'abcFBIabcCIAabc' r = re.findall('fbi',a,re.I) print(r) # ['FBI'] # 多個模式之間用 | 連線在一起 import re a = 'abcFBI\nabcCIAabc' r = re.findall('fbi.{1}',re.I | re.S) # 匹配fbi然後匹配任意一個字元包括\n print(r) # ['FBI\n']
二、方法
re.findall
- 匹配出字串中所有 與制定值相關的值
- 以列表的形式返回
- 未匹配則返回空列表
import re re.findall(pattern,string,flags=0) pattern.findall(string[,pos[,endpos]])
import re line = "111aaabbb222小呼嚕奧利奧" r = re.findall('[0-9]',line) print(r) # ['1','1客棧','2']
re.match
- re.match 嘗試從字串的起始位置匹配一個模式
- 如果不是起始位置匹配成功的話,match()就返回none。
re.match(pattern,flags=0) # (標準,要匹配的,標誌位)
print(re.match('www','www.xxxx.com')) print(re.match('www','www.xxxx.com').span()) print(re.match('com','www.xxxx.com'))
<re.Match object; span=(0,3),match='www'> (0,3) None
group匹配物件
import re a = 'life is short,i use python,i love python' r = re.search('life(.*)python(.*)python',a) print(r.group(0)) # 完整正則匹配 ,life is short,i love python print(r.group(1)) # 第1個分組之間的取值 is short,i use print(r.group(2)) # 第2個分組之間的取值,i love print(r.group(0,1,2)) # 以元組形式返回3個結果取值 ('life is short,i love python',' is short,i use ',',i love ') print(r.groups()) # 返回就是group(1)和group(2) (' is short,i love ')
import re # .* 表示任意匹配除換行符(\n、\r)之外的任何單個或多個字元 # (.*?) 表示"非貪婪"模式,只儲存第一個匹配到的子串 # re.M 多行匹配,影響 ^ 和 $ # re.I 使匹配對大小寫不敏感 line = "Cats are smarter than dogs" matchObj1 = re.match(r'(.*) are (.*?) .*',line,re.M|re.I) matchObj2 = re.match(r'(.*) smarter (.*?) .*',re.M|re.I) matchObj3 = re.match(r'(.*) than (.*)',re.M|re.I) print(matchObj1) print(matchObj2) print(matchObj3) # <re.Match object; span=(0,26),match='Cats are smarter than dogs'> # <re.Match object; span=(0,match='Cats are smarter than dogs'> # None if matchObj1: print ("matchObj1.group() : ",matchObj1.group()) print ("matchObj1.group(1) : ",matchObj1.group(1)) print ("matchObj1.group(2) : ",matchObj1.group(2)) else: print ("No match!!") if matchObj2: print ("matchObj2.group() : ",matchObj2.group()) print ("matchObj2.group(1) : ",matchObj2.group(1)) print ("matchObj2.group(2) : ",matchObj2.group(2)) else: print ("No match!!") if matchObj3: print ("matchObj3.group() : ",matchObj3.group()) print ("matchObj3.group(1) : ",matchObj3.group(1)) print ("matchObj3.group(2) : ",matchObj3.group(2)) else: print ("No match!!") # matchObj1.group() : Cats are smarter than dogs # matchObj1.group(1) : Cats # matchObj1.group(2) : smarter # matchObj2.group() : Cats are smarter than dogs # matchObj2.group(1) : Cats are # matchObj2.group(2) : than # matchObj3.group() : Cats are smarter than dogs # matchObj3.group(1) : Cats are smarter # matchObj3.group(2) : dogs
import re # 點 是匹配單個字元 # 星是前面的東西出現0次或無數次 # 點星就是任意字元出現0次或無數次 str = "a b a b" matchObj1 = re.match(r'a(.*)b',str,re.M|re.I) matchObj2 = re.match(r'a(.*?)b',re.M|re.I) print("matchObj1.group() : ",matchObj1.group()) print("matchObj2.group() : ",matchObj2.group()) # matchObj1.group() : a b a b # matchObj2.group() : a b
re.search
掃描整個字串並返回第一個成功的匹配。
re.search(pattern,flags=0)
import re line = "cats are smarter than dogs" matchObj = re.match(r'dogs',re.M|re.I) matchObj1= re.search(r'dogs',re.M|re.I) matchObj2= re.match(r'(.*) dogs',re.M|re.I) if matchObj: print ("match --> matchObj.group() : ",matchObj.group()) else: print ("No match!!") if matchObj1: print ("match --> matchttp://www.cppcns.comhObj1.group() : ",matchObj1.group()) else: print ("No match!!") if matchObj2: print ("match --> matchO程式設計客棧bj2.group() : ",matchObj2.group()) else: print ("No match!!") # No match!! # match --> matchObj1.group() : dogs # match --> matchObj2.group() : cats are smarter than dogs
re.compile
- re.compile是將正則表示式轉換為模式物件
- 這樣可以更有效率匹配。使用compile轉換一次之後,以後每次使用模式時就不用進行轉換
三、檢索和替換
re.sub 替換字串
re.sub('被替換的','替換成的',a)
# 把FBI替換成BBQ import re a = 'abcFBIabcCIAabc' r = re.sub('FBI','BBQ',a) print(r) # 把FBI替換成BBQ,第4引數寫1,證明只替換第一次,預設是0(無限替換) import re a = 'abcFBIabcFBIaFBICIAabc' r = re.sub('FBI',1) print(r) # abcBBQabcCIAabc # abcBBQabcFBIaFBICIAabc
# 把函式當引數傳到sub的列表裡,實現把業務交給函式去處理,例如將FBI替換成$FBI$ import re a = 'abcFBIabcFBIaFBICIAabc' def 函式名(形參): 分段獲取 = 形參.group() # group()在正則表示式中用於獲取分段截獲的字串,獲取到FBI return '$' + 分段獲取 + '$' r = re.sub('FBI',函式名,a) print(r)
總結
本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注我們的更多內容!