Python開發【模組】:re正則,python開發re
re模組
序言:
re模組用於對python的Regex的操作
'.' 預設匹配除\n之外的任意一個字元,若指定flag DOTALL,則匹配任一字元,包括換行'^' 匹配字元開頭,若指定flags MULTILINE,這種也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)'$' 匹配字元結尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以'*' 匹配*號前的字元0次或多次,re.findall("ab*","cabb3abcbbac") 結果為['abb', 'ab', 'a']'+' 匹配前一個字元1次或多次,re.findall("ab+","ab+cd+abb+bba") 結果['ab', 'abb']'?' 匹配前一個字元1次或0次'{m}' 匹配前一個字元m次'{n,m}' 匹配前一個字元n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果'abb', 'ab', 'abb']'|' 匹配|左或|右的字元,re.search("abc|ABC","ABCBabcCD").group() 結果'ABC''(...)' 分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結果 abcabca456c'[a-z]' 匹配a到z任意一個字元'[^()]' 匹配除()以外的任意一個字元 r' ' 轉義引號裡的字元 針對\字元 詳情查看⑦'\A' 只從字元開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的'\Z' 匹配字元結尾,同$'\d' 匹配數字0-9'\D' 匹配非數字'\w' 匹配[A-Za-z0-9]'\W' 匹配非[A-Za-z0-9]'\s' 匹配空白字元、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 結果 '\t' '(?P<name>...)' 分組匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city")結果{'province': '3714', 'city': '81', 'birthday': '1993'}re.IGNORECASE 忽略大小寫 re.search('(\A|\s)red(\s+|$)',i,re.IGNORECASE)
標誌位即模式修正符,不改變Regex的情況下,通過模式修正符改變Regex的含義,從而實現一些匹配結果的調整等功能:
# flagsI = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case 匹配時忽略大小寫L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale 做本地化識別匹配U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale 根據Unicode字元及解析字元M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline 多行匹配S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline 讓.匹配包括分行符號,即用了該模式修正後,"."匹配就可以匹配任意的字元了X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
貪婪模式、懶惰模式:
import reresult1 = re.search("p.*y","abcdfphp435pythony_py") # 貪婪模式print(result1)# <_sre.SRE_Match object; span=(5, 21), match='php435pythony_py'>result2 = re.search("p.*?y","abcdfphp435pythony_py") # 懶惰模式print(result2)# <_sre.SRE_Match object; span=(5, 13), match='php435py'>
match:
從起始位置開始根據模型去字串中匹配指定內容:
#matchimport re obj = re.match('\d+', '123uua123sf') #從第一個字元開始匹配一個到多個數字print(obj) #<_sre.SRE_Match object; span=(0, 3), match='123'>if obj: #如果有匹配到字元則執行,為空白不執行 print(obj.group()) #列印匹配到的內容#123
匹配ip地址:
import reip = '255.255.255.253'result=re.match(r'^([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.' r'([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$',ip)print(result)# <_sre.SRE_Match object; span=(0, 15), match='255.255.255.253'>
search:
根據模型去字串中匹配指定內容(不一定是最開始位置),匹配最前
#searchimport reobj = re.search('\d+', 'a123uu234asf') #從數字開始匹配一個到多個數字print(obj)#<_sre.SRE_Match object; span=(1, 4), match='123'>if obj: #如果有匹配到字元則執行,為空白不執行 print(obj.group()) #列印匹配到的內容#123import reobj = re.search('\([^()]+\)', 'sdds(a1fwewe2(3uusfdsf2)34as)f') #匹配最裡面()的內容print(obj)#<_sre.SRE_Match object; span=(13, 24), match='(3uusfdsf2)'>if obj: #如果有匹配到字元則執行,為空白不執行 print(obj.group()) #列印匹配到的內容#(3uusfdsf2)
group與groups的區別:
#group與groups的區別import rea = "123abc456"b = re.search("([0-9]*)([a-z]*)([0-9]*)", a)print(b)#<_sre.SRE_Match object; span=(0, 9), match='123abc456'>print(b.group())#123abc456print(b.group(0))#123abc456print(b.group(1))#123print(b.group(2))#abcprint(b.group(3))#456print(b.groups())#('123', 'abc', '456')
findall:
上述兩中方式均用於匹配單值,即:只能匹配字串中的一個,如果想要匹配到字串中所有合格元素,則需要使用 findall;findall沒有group用法
#findallimport reobj = re.findall('\d+', 'a123uu234asf') #匹配多個if obj: #如果有匹配到字元則執行,為空白不執行 print(obj) #產生的內容為列表#['123', '234']
sub:
用於替換匹配的字串(pattern, repl, string, count=0, flags=0)
#subimport recontent = "123abc456"new_content = re.sub('\d+', 'ABC', content)print(new_content)#ABCabcABC
split:
根據指定匹配進行分組(pattern, string, maxsplit=0, flags=0)
#splitimport recontent = "1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )"new_content = re.split('\*', content) #用*進行分割,分割為列表print(new_content)#['1 - 2 ', ' ((60-30+1', '(9-2', '5/3+7/3', '99/4', '2998+10', '568/14))-(-4', '3)/(16-3', '2) )']content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_content = re.split('[\+\-\*\/]+', content)# new_content = re.split('\*', content, 1)print(new_content)#["'1 ", ' 2 ', ' ((60', '30', '1', '(9', '2', '5', '3', '7', '3', '99', '4', '2998', '10', '568', '14))',# '(', '4', '3)', '(16', '3', "2) )'"]inpp = '1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))'inpp = re.sub('\s*','',inpp) #把空白字元去掉print(inpp)new_content = re.split('\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+){1}\)', inpp, 1)print(new_content)#['1-2*((60-30+', '-40-5', '*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
補充r' ' 轉義:
fdfdsfds\fdssfdsfds& @$
lzl.py
首先要清楚,程式讀取檔案裡的\字元時,添加到列表裡面的是\\:
import re,sysli = []with open('lzl.txt','r',encoding="utf-8") as file: for line in file: li.append(line)print(li) # 注意:檔案中的單斜杠,讀出來後會變成雙斜杠# ['fdfdsfds\\fds\n', 'sfdsfds& @$']print(li[0]) # print列印的時候還是單斜杠# fdfdsfds\fds
r字元的意義,對字元\進行轉義,\只做為字元出現:
import re,sysli = []with open('lzl.txt','r',encoding="utf-8") as file: for line in file: print(re.findall(r's\\f', line)) #第一種方式匹配 # print(re.findall('\\\\', line)) #第二種方式匹配 li.append(line)print(li) # 注意:檔案中的單斜杠,讀出來後會變成雙斜杠# ['s\\f']# []# ['fdfdsfds\\fds\n', 'sfdsfds& @$']
補充:看完下面的代碼你可能更懵了
import rere.findall(r'\\', line) # 正則中只能這樣寫 不能寫成 r'\' 這樣print(r'\\') # 只能這樣寫 不能寫成r'\' \只能是雙數# \\ 結果# 如果想值列印單個\ 寫成如下print('\\') # 只能是雙數# \ 結果
總結:檔案中的單斜杠\,讀出到程式中時是雙斜杠\\,print列印出來是單斜杠\;正則匹配檔案但斜杠\時,用r'\\'雙斜杠去匹配,或者不用r直接用'\\\\'四個斜杠去匹配
compile函數:
說明:
Python通過re模組提供對Regex的支援。使用re的一般步驟是先使用re.compile()函數,將Regex的字串形式編譯為Pattern執行個體,然後使用Pattern執行個體處理文本並獲得匹配結果(一個Match執行個體),最後使用Match執行個體獲得資訊,進行其他的操作
舉一個簡單的例子,在尋找一個字串中所有的英文字元:
import repattern = re.compile('[a-zA-Z]')result = pattern.findall('as3SiOPdj#@23awe')print(result)# ['a', 's', 'S', 'i', 'O', 'P', 'd', 'j', 'a', 'w', 'e']
匹配IP地址(255.255.255.255):
import repattern = re.compile(r'^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$')result = pattern.match('255.255.255.255')print(result)# <_sre.SRE_Match object; span=(0, 15), match='255.255.255.255'>