正則表達式並非Python的一部分。正則表達式是用於處理字符串的強大工具,擁有本身獨特的語法以及一個獨立的處理引擎,效率上可能不如str自帶的方法,但功能十分強大。得益於這一點,在提供了正則表達式的語言裏,正則表達式的語法都是同樣的,區別只在於不一樣的編程語言實現支持的語法數量不一樣;但不用擔憂,不被支持的語法一般是不經常使用的部分。若是已經在其餘語言裏使用過正則表達式,只須要簡單看一看就能夠上手了。git
在這裏仍是要推薦下我本身建的Python開發學習羣:725479218,羣裏都是學Python開發的,若是你正在學習Python ,小編歡迎你加入,你們都是軟件開發黨,不按期分享乾貨(只有Python軟件開發相關的),包括我本身整理的一份2018最新的Python進階資料和高級開發教程,歡迎進階中和進想深刻Python的小夥伴程序員
下圖展現了使用正則表達式進行匹配的流程: 正則表達式
正則表達式的大體匹配過程是:依次拿出表達式和文本中的字符比較,若是每個字符都能匹配,則匹配成功;一旦有匹配不成功的字符則匹配失敗。若是表達式中有量詞或邊界,這個過程會稍微有一些不一樣,但也是很好理解的,看下圖中的示例以及本身多使用幾回就能明白。編程
下圖列出了Python支持的正則表達式元字符和語法: 編程語言
正則表達式一般用於在文本中查找匹配的字符串。Python裏數量詞默認是貪婪的(在少數語言裏也多是默認非貪婪),老是嘗試匹配儘量多的字符;非貪婪的則相反,老是嘗試匹配儘量少的字符。例如:正則表達式"ab*"若是用於查找"abbbc",將找到"abbb"。而若是使用非貪婪的數量詞"ab*?",將找到"a"。工具
與大多數編程語言相同,正則表達式裏使用""做爲轉義字符,這就可能形成反斜槓困擾。假如你須要匹配文本中的字符"",那麼使用編程語言表示的正則表達式裏將須要4個反斜槓"\\":前兩個和後兩個分別用於在編程語言裏轉義成反斜槓,轉換成兩個反斜槓後再在正則表達式裏轉義成一個反斜槓。Python裏的原生字符串很好地解決了這個問題,這個例子中的正則表達式可使用r"\"表示。一樣,匹配一個數字的"\d"能夠寫成r"\d"。有了原生字符串,你不再用擔憂是否是漏寫了反斜槓,寫出來的表達式也更直觀。學習
正則表達式提供了一些可用的匹配模式,好比忽略大小寫、多行匹配等,這部份內容將在Pattern類的工廠方法re.compile(pattern[, flags])中一塊兒介紹。spa
Python經過re模塊提供對正則表達式的支持。使用re的通常步驟是先將正則表達式的字符串形式編譯爲Pattern實例,而後使用Pattern實例處理文本並得到匹配結果(一個Match實例),最後使用Match實例得到信息,進行其餘的操做。code
# encoding: UTF-8 import re # 將正則表達式編譯成Pattern對象 pattern = re.compile(r'hello') # 使用Pattern匹配文本,得到匹配結果,沒法匹配時將返回None match = pattern.match('hello world!') if match: # 使用Match得到分組信息 print match.group() ### 輸出 ### # hello
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"># encoding: UTF-8 import re # 將正則表達式編譯成Pattern對象 pattern = re.compile(r'hello') # 使用Pattern匹配文本,得到匹配結果,沒法匹配時將返回None match = pattern.match('hello world!') if match: # 使用Match得到分組信息 print match.group() ### 輸出 ### # hello</pre>對象
a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X) b = re.compile(r"\d+\.\d*")
re.compile(strPattern[, flag]):
這個方法是Pattern類的工廠方法,用於將字符串形式的正則表達式編譯爲Pattern對象。 第二個參數flag是匹配模式,取值可使用按位或運算符'|'表示同時生效,好比re.I | re.M。另外,你也能夠在regex字符串中指定模式,好比re.compile('pattern', re.I | re.M)與re.compile('(?im)pattern')是等價的。 可選值有:
re提供了衆多模塊方法用於完成正則表達式的功能。這些方法可使用Pattern實例的相應方法替代,惟一的好處是少寫一行re.compile()代碼,但同時也沒法複用編譯後的Pattern對象。這些方法將在Pattern類的實例方法部分一塊兒介紹。如上面這個例子能夠簡寫爲:
re模塊還提供了一個方法escape(string),用於將string中的正則表達式元字符如*/+/?等以前加上轉義符再返回,在須要大量匹配元字符時有那麼一點用。
Match對象是一次匹配的結果,包含了不少關於這次匹配的信息,可使用Match提供的可讀屬性或方法來獲取這些信息。
屬性:
方法:
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!
Pattern對象是一個編譯好的正則表達式,經過Pattern提供的一系列方法能夠對文本進行匹配查找。
Pattern不能直接實例化,必須使用re.compile()進行構造。
Pattern提供了幾個可讀屬性用於獲取表達式的相關信息:
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模塊方法]:
# encoding: UTF-8 import re # 將正則表達式編譯成Pattern對象 pattern = re.compile(r'world') # 使用search()查找匹配的子串,不存在能匹配的子串時將返回None # 這個例子中使用match()沒法成功匹配 match = pattern.search('hello world!') if match: # 使用Match得到分組信息 print match.group() ### 輸出 ### # world
3. split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]): 按照可以匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將所有分割。
import re p = re.compile(r'\d+') print p.split('one1two2three3four4') ### output ### # ['one', 'two', 'three', 'four', '']
4. findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 搜索string,以列表形式返回所有能匹配的子串。
import re p = re.compile(r'\d+') print p.findall('one1two2three3four4') ### output ### # ['1', '2', '3', '4']
5. 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(), ### output ### # 1 2 3 4
6. 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) ### output ### # say i, world hello! # I Say, Hello World!
7. subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]): 返回 (sub(repl, string[, count]), 替換次數)。
以上就是Python對於正則表達式的支持。熟練掌握正則表達式是每個程序員必須具有的技能,這年頭沒有不與字符串打交道的程序了。筆者也處於初級階段,與君共勉,^_^
另外,圖中的特殊構造部分沒有舉出例子,用到這些的正則表達式是具備必定難度的。有興趣能夠思考一下,如何匹配不是以abc開頭的單詞,^_^