Python正则表达式-2
本文介紹了Python對于正則表達式的支持,包括正則表達式基礎以及Python正則表達式標準庫的完整介紹及使用示例。本文的內容不包括如何編寫高效的正則表達式、如何優化正則表達式,這些主題請查看其他教程。
注意:本文基于Python2.4完成;如果看到不明白的詞匯請記得百度谷歌或維基,whatever。
尊重作者的勞動,轉載請注明作者及原文地址 >.<html
最短匹
1. 正則表達式基礎
1.1. 簡單介紹
正則表達式并不是Python的一部分。正則表達式是用于處理字符串的強大工具,擁有自己獨特的語法以及一個獨立的處理引擎,效率上可能不如str自帶的方法,但功能十分強大。得益于這一點,在提供了正則表達式的語言里,正則表達式的語法都是一樣的,區別只在于不同的編程語言實現支持的語法數量不同;但不用擔心,不被支持的語法通常是不常用的部分。如果已經在其他語言里使用過正則表達式,只需要簡單看一看就可以上手了。
下圖展示了使用正則表達式進行匹配的流程:
正則表達式的大致匹配過程是:依次拿出表達式和文本中的字符比較,如果每一個字符都能匹配,則匹配成功;一旦有匹配不成功的字符則匹配失敗。如果表達式中有量詞或邊界,這個過程會稍微有一些不同,但也是很好理解的,看下圖中的示例以及自己多使用幾次就能明白。
下圖列出了Python支持的正則表達式元字符和語法:??
1.2. 數量詞的貪婪模式與非貪婪模式
正則表達式通常用于在文本中查找匹配的字符串。Python里數量詞默認是貪婪的(在少數語言里也可能是默認非貪婪),總是嘗試匹配盡可能多的字符;非貪婪的則相反,總是嘗試匹配盡可能少的字符。例如:正則表達式"ab*"如果用于查找"abbbc",將找到"abbb"。而如果使用非貪婪的數量詞"ab*?",將找到"a"。
Jeffrey: 我加一點自己做項目過程中遇到的這種匹配方式的理解:
最短匹配:.*??http://deerchao.net/tutorials/regex/regex.htm?
假如,我們有以下的代碼存放在Test_1.xml中(注意:這里不僅限于xml文件,同樣的也適應于其它的任何的文件):我們的
源文件:
<Request Action="LOGIN" RequestId="100000"><Authentication><ClientName>Administrator</ClientName><Password>5420!Cts</Password></Authentication></Request><?xml version="1.0" encoding="UTF-8"?><Response Status="OKAY" RequestId="100000"><Authentication MajorVersion="28" MinorVersion="0"><ClientName>Administrator</ClientName><Role>ADMINISTRATOR</Role></Authentication></Response><Request Action="UPDATE" RequestId="100000"><CapacityLimit><Category>RESIDENTIALSUBSCRIBER_R2</Category><LockKey>17ylvJrPbcGgHEUPF001n//k/v/n//Xu0P//AAb3rb8H=0000050010</LockKey><SignKey>QDA9s+3HukQn3DyX15otQNaOvEQaEU5skCx0JDPQHJ77/jwYQl0uLQUYlKHZWmwKIhGCGWIuz8nADDtXlJK9VA==</SignKey></CapacityLimit></Request><?xml version="1.0" encoding="UTF-8"?><span style="color:#FF0000;"><Response Status="OKAY" CongLvl="LEVEL0" OverallProvTime="4026852" TimeInReqQueue="228" DbCommitTime="6371" RequestId="100000"> <CapacityParms><Category>RESIDENTIALSUBSCRIBER_R2</Category><FeatureSetName>R1 FEATURE SET</FeatureSetName><OfficeId>ylvJrPbcGgHE</OfficeId><CurrentCnt>0</CurrentCnt><LimitCnt>0000050</LimitCnt><SpareCapacity>0</SpareCapacity><TasUnequalDistribution>0</TasUnequalDistribution> </CapacityParms></Response></span><Request Action="LOGOFF" RequestId="tll-logoff"><Authentication><ClientName>Administrator</ClientName></Authentication></Request><?xml version="1.0" encoding="UTF-8"?><Response Status="OKAY" RequestId="tll-logoff"><Authentication><ClientName>Administrator</ClientName></Authentication></Response> 這個是我的re_test.py代碼文件,這個文件中到了兩種匹配方式,當然,只有def re_testsearch()才可以滿足我們的要求,因為它是實現的是段落匹配(因為這個里面用了 re.S)#-*- coding:utf-8 -*- #最上一句如果不加上的話不能輸入漢字,不然編譯不過 #/usr/bin/pythonimport os import sys import re#################################################### # 一行一行的匹配 # 比如Test_2.xml中的內容如下: # <Response Staus="OKAY" CongLvl="jeffrey"> # <a>test1</a> # <b>test2</b> # </Response> # <Response Staus="OKAY" CongLvl="guan"> # <a>test1</a> # <b>test2</b> # </Response> # <Response Staus="OKAY" CongLvl="zenghui"> # <a>test1</a> # <b>test2</b> # </Response> # <Response Staus="OKAY" CongLvl="jeguan"> # <a>test1</a> # <b>test2</b> # </Response> # 那么匹配后的得到結果為 # <Response Staus="OKAY" CongLvl="jeffrey"> # <Response Staus="OKAY" CongLvl="guan"> # <Response Staus="OKAY" CongLvl="zenghui"> # <Response Staus="OKAY" CongLvl="jeguan"> # #################################################### def re_test():# 原文件filename = r'C:\Users\jeguan\Desktop\Test_2.xml'# 匹配得到的內容存儲在Test_2_bk.xml中new_file = r'C:\Users\jeguan\Desktop\Test_2_bk.xml'# 打開原文件open_file = open(filename, 'r')read_file = open_file.readlines()# 打開目標文件,即:存放匹配結果的文件newfile = open(new_file, 'wb')# 匹配以<Response開頭并且有CongLvl字符串的行,注意,# 這里是非lazzy匹配,并且是一行一行匹配,即,遇到# '\n'就會結束patt = re.compile(r'^<Response.*CongLvl.*')# 遍歷原文件的所有行,如果找到就會存盤for line in read_file:match = patt.search(line)if match:m = match.group(0)newfile.write(m)open_file.close()newfile.close()################################################################################# # 多行匹配,即:可以匹配一個文本中的特定段落。這里主要是要用到re模塊中的re.S # 它表示當用'.'來進行匹配的時候,可以忽略掉'\n',這一點與'.'正常的規則是不一樣的 # # 另外一個要注意的地方是這里使用了Lazzy匹配的方式。當有多個Response>出現的時候, # 它只會匹配第一次出現的地方。比如: # <Response Staus="OKAY" CongLvl="jeguan"> # <a>test1</a> # <b>test2</b> # </Response> # <Response Staus="OKAY" CongLvl="zenghuiguan"> # <a>test3</a> # <b>test4</b> # </Response> # 當用lazzy方式的時候,只會匹配到第一次出現Response>的地方 # 本文中匹配得到的結果為: # <Response Staus="OKAY" CongLvl="jeguan"> # <a>test1</a> # <b>test2</b> # </Response> # ################################################################################ def re_testsearch():# filename = r'C:\Users\jeguan\Desktop\Test_2.xml'new_file = r'C:\Users\jeguan\Desktop\Test_2_bk.xml'open_file = open(filename, 'r')read_file = open_file.readlines()newfile = open(new_file, 'wb')# re.S means: Make the '.' special character match any character at all, # including a newline; without this flag, '.' will match anything except a newline.# '(.+?)' means: this is a greedy match. When the fist 'Response>' is found, then# it will not try to match the next 'Response>'<span style="color:#CC0000;">patt = re.compile(r'<Response Status="OKAY" CongLvl="LEVEL0"*(.+?)Response>', <strong>re.S</strong>)</span>str1 = ""# 把讀出的行放在str1中for line in read_file:str1 = str1 + linematch1 = patt.search(str1)newfile.write(match1.group(0))print(match1.group())if __name__ == "__main__":re_testsearch()我們用re_testsearch()這個函數來匹配最終的結果如下所示,得到了我們的要求:
<Response Status="OKAY" CongLvl="LEVEL0" OverallProvTime="4026852" TimeInReqQueue="228" DbCommitTime="6371" RequestId="100<CapacityParms><Category>RESIDENTIALSUBSCRIBER_R2</Category><FeatureSetName>R1 FEATURE SET</FeatureSetName><OfficeId>ylvJrPbcGgHE</OfficeId><CurrentCnt>0</CurrentCnt><LimitCnt>0000050</LimitCnt><SpareCapacity>0</SpareCapacity><TasUnequalDistribution>0</TasUnequalDistribution></CapacityParms> </Response> 但是,如果我們使用re_test()來試圖匹配的話,不會得到上面的這個結果,相反,只會找到 <Response Status="OKAY" CongLvl="LEVEL0" OverallProvTime="4026852" TimeInReqQueue="228" DbCommitTime="6371" RequestId="100000">
上面的代碼可以在我的github上找到:https://github.com/double12gzh/PythonLearning
1.3. 反斜杠的困擾
與大多數編程語言相同,正則表達式里使用"\"作為轉義字符,這就可能造成反斜杠困擾。假如你需要匹配文本中的字符"\",那么使用編程語言表示的正則表達式里將需要4個反斜杠"\\\\":前兩個和后兩個分別用于在編程語言里轉義成反斜杠,轉換成兩個反斜杠后再在正則表達式里轉義成一個反斜杠。Python里的原生字符串很好地解決了這個問題,這個例子中的正則表達式可以使用r"\\"表示。同樣,匹配一個數字的"\\d"可以寫成r"\d"。有了原生字符串,你再也不用擔心是不是漏寫了反斜杠,寫出來的表達式也更直觀。
1.4. 匹配模式
正則表達式提供了一些可用的匹配模式,比如忽略大小寫、多行匹配等,這部分內容將在Pattern類的工廠方法re.compile(pattern[, flags])中一起介紹。
2. re模塊
2.1. 開始使用re
Python通過re模塊提供對正則表達式的支持。使用re的一般步驟是先將正則表達式的字符串形式編譯為Pattern實例,然后使用Pattern實例處理文本并獲得匹配結果(一個Match實例),最后使用Match實例獲得信息,進行其他的操作。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # encoding: UTF-8 import re # 將正則表達式編譯成Pattern對象 pattern =re.compile(r'hello') # 使用Pattern匹配文本,獲得匹配結果,無法匹配時將返回None match =pattern.match('hello world!') if match: ????# 使用Match獲得分組信息 ????printmatch.group() ### 輸出 ### # hello |
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): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,并可以加入注釋。以下兩個正則表達式是等價的:
| 1 2 3 4 | 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類的實例方法部分一起介紹。如上面這個例子可以簡寫為:
| 1 2 | m =re.match(r'hello','hello world!') print m.group() |
re模塊還提供了一個方法escape(string),用于將string中的正則表達式元字符如*/+/?等之前加上轉義符再返回,在需要大量匹配元字符時有那么一點用。
2.2. Match
Match對象是一次匹配的結果,包含了很多關于此次匹配的信息,可以使用Match提供的可讀屬性或方法來獲取這些信息。
屬性:
方法:
獲得一個或多個分組截獲的字符串;指定多個參數時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最后一次截獲的子串。
以元組形式返回全部分組截獲的字符串。相當于調用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認為None。
返回以有別名的組的別名為鍵、以該組截獲的子串為值的字典,沒有別名的組不包含在內。default含義同上。
返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認值為0。
返回指定的組截獲的子串在string中的結束索引(子串最后一個字符的索引+1)。group默認值為0。
返回(start(group), end(group))。
將匹配到的分組代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。\id與\g<id>是等價的;但\10將被認為是第10個分組,如果你想表達\1之后是字符'0',只能使用\g<1>0。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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') ### output ### # m.string: hello world! # m.re: <_sre.SRE_Pattern object at 0x016E1A38> # 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! |
2.3. Pattern
Pattern對象是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。
Pattern不能直接實例化,必須使用re.compile()進行構造。
Pattern提供了幾個可讀屬性用于獲取表達式的相關信息:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 ### output ### # p.pattern: (\w+) (\w+)(?P<sign>.*) # p.flags: 16 # p.groups: 3 # p.groupindex: {'sign': 3} |
實例方法[ | re模塊方法]:
這個方法將從string的pos下標處起嘗試匹配pattern;如果pattern結束時仍可匹配,則返回一個Match對象;如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。
pos和endpos的默認值分別為0和len(string);re.match()無法指定這兩個參數,參數flags用于編譯pattern時指定匹配模式。
注意:這個方法并不是完全匹配。當pattern結束時若string還有剩余字符,仍然視為成功。想要完全匹配,可以在表達式末尾加上邊界匹配符'$'。
示例參見2.1小節。
這個方法用于查找字符串中可以匹配成功的子串。從string的pos下標處起嘗試匹配pattern,如果pattern結束時仍可匹配,則返回一個Match對象;若無法匹配,則將pos加1后重新嘗試匹配;直到pos=endpos時仍無法匹配則返回None。
pos和endpos的默認值分別為0和len(string));re.search()無法指定這兩個參數,參數flags用于編譯pattern時指定匹配模式。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # encoding: UTF-8 import re # 將正則表達式編譯成Pattern對象 pattern =re.compile(r'world') # 使用search()查找匹配的子串,不存在能匹配的子串時將返回None # 這個例子中使用match()無法成功匹配 match =pattern.search('hello world!') if match: ????# 使用Match獲得分組信息 ????printmatch.group() ### 輸出 ### # world |
按照能夠匹配的子串將string分割后返回列表。maxsplit用于指定最大分割次數,不指定將全部分割。
| 1 2 3 4 5 6 7 | import re p =re.compile(r'\d+') print p.split('one1two2three3four4') ### output ### # ['one', 'two', 'three', 'four', ''] |
搜索string,以列表形式返回全部能匹配的子串。
| 1 2 3 4 5 6 7 | import re p =re.compile(r'\d+') print p.findall('one1two2three3four4') ### output ### # ['1', '2', '3', '4'] |
搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。
| 1 2 3 4 5 6 7 8 | import re p =re.compile(r'\d+') for m in p.finditer('one1two2three3four4'): ????printm.group(), ### output ### # 1 2 3 4 |
使用repl替換string中每一個匹配的子串后返回替換后的字符串。
當repl是一個字符串時,可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),并返回一個字符串用于替換(返回的字符串中不能再引用分組)。
count用于指定最多替換次數,不指定時全部替換。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import re p =re.compile(r'(\w+) (\w+)') s ='i say, hello world!' print p.sub(r'\2 \1', s) def func(m): ????returnm.group(1).title()+' ' + m.group(2).title() print p.sub(func, s) ### output ### # say i, world hello! # I Say, Hello World! |
返回 (sub(repl, string[, count]), 替換次數)。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import re p =re.compile(r'(\w+) (\w+)') s ='i say, hello world!' print p.subn(r'\2 \1', s) def func(m): ????returnm.group(1).title()+' ' + m.group(2).title() print p.subn(func, s) ### output ### # ('say i, world hello!', 2) # ('I Say, Hello World!', 2) |
以上就是Python對于正則表達式的支持。熟練掌握正則表達式是每一個程序員必須具備的技能,這年頭沒有不與字符串打交道的程序了。筆者也處于初級階段,與君共勉,^_^
另外,圖中的特殊構造部分沒有舉出例子,用到這些的正則表達式是具有一定難度的。有興趣可以思考一下,如何匹配不是以abc開頭的單詞,^_^
全文結束
轉載于:https://www.cnblogs.com/double12gzh/p/10166238.html
總結
以上是生活随笔為你收集整理的Python正则表达式-2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Noip模拟赛] Polygon
- 下一篇: WCF - WAS Hosting