一、正則re
1.正則表達式定義
正則就是用一些具有特殊含義的符號組合到一起(稱為正則表達式)來描述字符或者字符串的方法。或者說:正則就是用來描述一類事物的規則。(在Python中)它內嵌在Python中,並通過 re 模塊實現。正則表達式模式被編譯成一系列的字節碼,然后由用 C 編寫的匹配引擎執行。
2.常用的正則表達式
3.貪婪模式與非貪婪模式
正則表達式通常用於在文本中查找匹配的字符串。Python里數量詞默認是貪婪的(在少數語言里也可能是默認非貪婪),總是嘗試匹配盡可能多的字符;非貪婪的則相反,總是嘗試匹配盡可能少的字符。例如:正則表達式"ab*"如果用於查找"abbbc",將找到"abbb"。而如果使用非貪婪的數量詞"ab*?",將找到"a"。
4.反斜杠
與大多數編程語言相同,正則表達式里使用"\"作為轉義字符,這就可能造成反斜杠困擾。假如你需要匹配文本中的字符"\",那么使用編程語言表示的正則表達式里將需要4個反斜杠"\\\\":前兩個和后兩個分別用於在編程語言里轉義成反斜杠,轉換成兩個反斜杠后再在正則表達式里轉義成一個反斜杠。Python里的原生字符串很好地解決了這個問題,這個例子中的正則表達式可以使用r"\\"表示。同樣,匹配一個數字的"\\d"可以寫成r"\d"。有了原生字符串,你再也不用擔心是不是漏寫了反斜杠,寫出來的表達式也更直觀。
5.re模塊
Python通過re模塊提供對正則表達式的支持。使用re的一般步驟是先將正則表達式的字符串形式編譯為Pattern實例,然后使用Pattern實例處理文本並獲得匹配結果(一個Match實例),最后使用Match實例獲得信息,進行其他的操作。
Match
Match對象是一次匹配的結果,包含了很多關於此次匹配的信息,可以使用Match提供的可讀屬性或方法來獲取這些信息。
屬性:
- string: 匹配時使用的文本。
- re: 匹配時使用的Pattern對象。
- pos: 文本中正則表達式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
- endpos: 文本中正則表達式結束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
- lastindex: 最后一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將為None。
- lastgroup: 最后一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將為None。
方法:
- group([group1, …]):
獲得一個或多個分組截獲的字符串;指定多個參數時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最后一次截獲的子串。
- groups([default]):
以元組形式返回全部分組截獲的字符串。相當於調用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認為None。
- groupdict([default]):
返回以有別名的組的別名為鍵、以該組截獲的子串為值的字典,沒有別名的組不包含在內。default含義同上。
- start([group]):
返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認值為0。
- end([group]):
返回指定的組截獲的子串在string中的結束索引(子串最后一個字符的索引+1)。group默認值為0。
- span([group]):
返回(start(group), end(group))。
- expand(template):
將匹配到的分組代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。\id與\g<id>是等價的;但\10將被認為是第10個分組,如果你想表達\1之后是字符'0',只能使用\g<1>0。
例:
import re m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!') print("m.string:", m.string) print("m.re:", m.re) print("m.pos:", m.pos) print("m.endpos:", m.endpos) print("m.lastindex:", m.lastindex) print("m.lastgroup:", m.lastgroup) print("m.group(1,2):", m.group(1, 2)) print("m.groups():", m.groups()) print("m.groupdict():", m.groupdict()) print("m.start(2):", m.start(2)) print("m.end(2):", m.end(2)) print("m.span(2):", m.span(2)) print(r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3'))
輸出
m.string: hello world! m.re: re.compile('(\\w+) (\\w+)(?P<sign>.*)') m.pos: 0 m.endpos: 12 m.lastindex: 3 m.lastgroup: sign m.group(1,2): ('hello', 'world') m.groups(): ('hello', 'world', '!') m.groupdict(): {'sign': '!'} m.start(2): 6 m.end(2): 11 m.span(2): (6, 11) m.expand(r'\2 \1\3'): world hello!
Pattern
Pattern對象是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。
Pattern不能直接實例化,必須使用re.compile()進行構造。
Pattern提供了幾個可讀屬性用於獲取表達式的相關信息:
- pattern: 編譯時用的表達式字符串。
- flags: 編譯時用的匹配模式。數字形式。
- groups: 表達式中分組的數量。
- groupindex: 以表達式中有別名的組的別名為鍵、以該組對應的編號為值的字典,沒有別名的組不包含在內。
例:
import re p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL) print("p.pattern:", p.pattern) print("p.flags:", p.flags) print("p.groups:", p.groups) print("p.groupindex:", p.groupindex)
輸出
p.pattern: (\w+) (\w+)(?P<sign>.*) p.flags: 48 p.groups: 3 p.groupindex: {'sign': 3}
實例方法[ | re模塊方法]:
- match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):
這個方法將從string的pos下標處起嘗試匹配pattern;如果pattern結束時仍可匹配,則返回一個Match對象;如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。
pos和endpos的默認值分別為0和len(string);re.match()無法指定這兩個參數,參數flags用於編譯pattern時指定匹配模式。
注意:這個方法並不是完全匹配。當pattern結束時若string還有剩余字符,仍然視為成功。想要完全匹配,可以在表達式末尾加上邊界匹配符'$'。
示例參見2.1小節。
- search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
這個方法用於查找字符串中可以匹配成功的子串。從string的pos下標處起嘗試匹配pattern,如果pattern結束時仍可匹配,則返回一個Match對象;若無法匹配,則將pos加1后重新嘗試匹配;直到pos=endpos時仍無法匹配則返回None。
pos和endpos的默認值分別為0和len(string));re.search()無法指定這兩個參數,參數flags用於編譯pattern時指定匹配模式。
import re # 將正則表達式編譯成Pattern對象
pattern = re.compile(r'world') # 使用search()查找匹配的子串,不存在能匹配的子串時將返回None # 這個例子中使用match()無法成功匹配
match = pattern.search('hello world!') if match: # 使用Match獲得分組信息
print(match.group())
輸出
world
- split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能夠匹配的子串將string分割后返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。
import re p = re.compile(r'\d+') print(p.split('one1two2three3four4'))
輸出
['one', 'two', 'three', 'four', '']
- findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。
import re p = re.compile(r'\d+') print(p.findall('one1two2three3four4'))
輸出
['1', '2', '3', '4']
- finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。
import re p = re.compile(r'\d+') for m in p.finditer('one1two2three3four4'): print(m.group(),)
輸出
1
2
3
4
- sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替換string中每一個匹配的子串后返回替換后的字符串。
當repl是一個字符串時,可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)。
count用於指定最多替換次數,不指定時全部替換。
import re p = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!'
print(p.sub(r'\2 \1', s)) def func(m): return m.group(1).title() + ' ' + m.group(2).title() print(p.sub(func, s))
輸出
say i, world hello!
I Say, Hello World!
- subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替換次數)。
import re p = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!'
print(p.subn(r'\2 \1', s)) def func(m): return m.group(1).title() + ' ' + m.group(2).title() print(p.subn(func, s))
('say i, world hello!', 2) ('I Say, Hello World!', 2)
- re.compile(strPattern[, flag]):
這個方法是Pattern類的工廠方法,用於將字符串形式的正則表達式編譯為Pattern對象。 第二個參數flag是匹配模式,取值可以使用按位或運算符'|'表示同時生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)與re.compile('(?im)pattern')是等價的。
可選值有:
- re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)
- M(MULTILINE): 多行模式,改變'^'和'$'的行為(參見上圖)
- S(DOTALL): 點任意匹配模式,改變'.'的行為
- L(LOCALE): 使預定字符類 \w \W \b \B \s \S 取決於當前區域設定
- U(UNICODE): 使預定字符類 \w \W \b \B \s \S \d \D 取決於unicode定義的字符屬性
- X(VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,並可以加入注釋。以下兩個正則表達式是等價的:
a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X) b = re.compile(r"\d+\.\d*")
re提供了眾多模塊方法用於完成正則表達式的功能。這些方法可以使用Pattern實例的相應方法替代,唯一的好處是少寫一行re.compile()代碼,但同時也無法復用編譯后的Pattern對象。這些方法將在Pattern類的實例方法部分一起介紹。如上面這個例子可以簡寫為:
m = re.match(r'hello', 'hello world!') print(m.group())
re模塊還提供了一個方法escape(string),用於將string中的正則表達式元字符如*/+/?等之前加上轉義符再返回,在需要大量匹配元字符時有那么一點用。
6.舉例常用的匹配方式
- \w與\W
import re print(re.findall('\w','hello hexin 123')) print(re.findall('\W','hello hexin 123'))
輸出
['h', 'e', 'l', 'l', 'o', 'h', 'e', 'x', 'i', 'n', '1', '2', '3'] [' ', ' ']
- \s與\S
import re print(re.findall('\s','hello hexin 123')) print(re.findall('\S','hello hexin 123'))
輸出
[' ', ' ', ' ', ' '] ['h', 'e', 'l', 'l', 'o', 'h', 'e', 'x', 'i', 'n', '1', '2', '3']
- \d與\D
import re print(re.findall('\d','hello hexin 123')) print(re.findall('\D','hello hexin 123'))
輸出
['1', '2', '3'] ['h', 'e', 'l', 'l', 'o', ' ', 'h', 'e', 'x', 'i', 'n', ' ']
- \A與\Z
import re print(re.findall('\Ahe','hello hexin 123')) print(re.findall('123\Z','hello hexin 123'))
輸出
['he'] ['123']
- \n與\t
import re print(re.findall(r'\n','hello hexin \n123')) print(re.findall(r'\t','hello heixn \t123'))
輸出
['\n'] ['\t']
- ^與$
import re print(re.findall('^h','hello hexin 123')) print(re.findall('3$','hello hexin 123'))
輸出
['h'] ['3']
- 重復匹配:| . | * | ? | .* | .*? | + | {n,m} |
print(re.findall('a.b','a1b')) print(re.findall('a.b','a\nb')) print(re.findall('a.b','a\nb',re.S)) print(re.findall('a.b','a\nb',re.DOTALL))
輸出
['a1b'] [] ['a\nb'] ['a\nb']
- *
import re print(re.findall('ab*','bbbbbbb')) print(re.findall('ab*','a'))
輸出
[] ['a']
- ?
import re print(re.findall('ab?','a')) print(re.findall('ab?','abbb'))
輸出
['a'] ['ab']
- 匹配所有包含小數在內的數字
import re print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3"))
輸出
['123', '1.13', '12', '1', '3']
- .*默認為貪婪匹配
print(re.findall('a.*b','a1b22222222b'))
輸出
['a1b22222222b']
- .*?為非貪婪匹配
import re print(re.findall('a.*?b','a1b22222222b'))
輸出
['a1b']
- +
import re print(re.findall('ab+','a')) print(re.findall('ab+','abbb'))
輸出
[] ['abbb']
- {n,m}
import re print(re.findall('ab{2}','abbb')) print(re.findall('ab{2,4}','abbb')) print(re.findall('ab{1,}','abbb')) print(re.findall('ab{0,}','abbb'))
輸出
['abb'] ['abbb'] ['abbb'] ['abbb']
- []
import re print(re.findall('a[1*-]b','a1b a*b a-b')) #[]內的都為普通字符了,且如果-沒有被轉意的話,應該放到[]的開頭或結尾
print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]內的^代表的意思是取反
print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]內的^代表的意思是取反
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]內的^代表的意思是取反
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]內的^代表的意思是取反
輸出
['a1b', 'a*b', 'a-b'] ['a=b'] ['a1b'] ['aeb'] ['aeb', 'aEb']
- ()
import re print(re.findall('ab+','ababab123'))
print(re.findall('(ab)+123','ababab123')) #匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','ababab123')) #findall的結果不是匹配的全部內容,而是組內的內容,?:可以讓結果為匹配的全部內容
輸出
['ab', 'ab', 'ab'] ['ab'] ['ababab123']
- \
print(re.findall('a\\c','a\c')) #對於正則來說a\\c確實可以匹配到a\c,但是在python解釋器讀取a\\c時,會發生轉義,然后交給re去執行,所以拋出異常
print(re.findall(r'a\\c','a\c')) #r代表告訴解釋器使用rawstring,即原生字符串,把我們正則內的所有符號都當普通字符處理,不要轉義
print(re.findall('a\\\\c','a\c')) #同上面的意思一樣,和上面的結果一樣都是['a\\c']
輸出
[] ['a\\c'] ['a\\c']
- |
import re
print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company')) #(?:)匹配完整
輸出
['ies', 'y']
['companies', 'company']
補充:
數字匹配
import re print(re.findall(r'-?\d+\.?\d*',"1-12*(60+(-40.35/5)-(-4*3))")) #找出所有數字['1', '-12', '60', '-40.35', '5', '-4', '3'] #使用|,先匹配的先生效,|左邊是匹配小數,而findall最終結果是查看分組,所有即使匹配成功小數也不會存入結果 #而不是小數時,就去匹配(-?\d+),匹配到的自然就是,非小數的數,在此處即整數 print(re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整數['1', '-2', '60', '', '5', '-4', '3']
總結:
盡量使用泛匹配模式.*
盡量使用非貪婪模式:.*?
使用括號得到匹配目標:用group(n)去取得結果
有換行符就用re.S:修改模式
模塊簡單使用
import re #1 print(re.findall('e','he make love') ) #['e', 'e', 'e'],返回所有滿足匹配條件的結果,放在列表里 #2 print(re.search('e','he make love').group()) #e,只到找到第一個匹配然后返回一個包含匹配信息的對象,該對象可以通過調用group()方法得到匹配的字符串,如果字符串沒有匹配,則返回None。 #3 print(re.match('e','he make love')) #None,同search,不過在字符串開始處進行匹配,完全可以用search+^代替match #4 print(re.split('[ab]','abcd')) #['', '', 'cd'],先按'a'分割得到''和'bcd',再對''和'bcd'分別按'b'分割 #5 print('===>',re.sub('a','A','he make love')) #===> he mAke love,不指定n,默認替換所有 print('===>',re.sub('a','A','he make love',1)) #===> he mAke love print('===>',re.sub('a','A','he make love',2)) #===> he mAke love print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','he make love')) #===> love make he print('===>',re.subn('a','A','he make love')) #===> ('he mAke love', 2),結果帶有總共替換的個數 #6 obj=re.compile('\d{2}') print(obj.search('abc123eeee').group()) #12 print(obj.findall('abc123eeee')) #['12'],重用了obj
輸出
['e', 'e', 'e'] e None ['', '', 'cd'] ===> he mAke love ===> he mAke love ===> he mAke love ===> love make he ===> ('he mAke love', 1) 12 ['12']