正則表達式(regular expression)是一種用形式化語法描述的文本匹配模式。在須要處理大量文本處理的應用中有普遍的使用,我沒使用的編輯器,IDE中的搜索經常使用正則表達式做爲搜索模式。玩過*nix系統的都知道如sed,grep,awk這類的命令,他們是很是強大的文本處理工具。幾乎全部的語言都有對正則表達式的支持,有的直接在語法中支持,有的使用擴展庫的形式。python使用的就是擴展庫re。python
import re pattern = "this" text = "Does this text match the pattern?" match = re.search(pattern, text) # 返回一個Match對象 print match.re.pattern # 要匹配的正則表達式"this" print match.string # 匹配的文本"Does this match the pattern?" print match.start() # 匹配的開始位置 5 print match.end() # 匹配的結束位置 9
import re regex = re.compile("this") text = "Does this text match the pattern?" match = regex.search(text) if match: print "match" match.group(0) #返回匹配的字符串 else: print "not match"
import re pattern = 'ab' text = 'abbaaabbbbaaaaaa' re.findall(pattern, text) # 返回['ab', 'ab']
import re pattern = 'ab' text = 'abbaaabbbbaaaaaa' match = re.finditer(pattern, text) for m in match: print m.start() print m.end()
以上的例子會分別輸出兩次匹配結果的起始位置和結束位置。正則表達式
正則匹配默認採用的是貪婪算法,也就是說會re在匹配的時候會利用盡量多的輸入,而使用?能夠關閉這種貪心行爲,只匹配最少的輸入。這以前先說下量詞。算法
量詞是爲了簡化正則表達式的讀寫而定義的,通用的形式是{m,n},這表示匹配的個數至少是m,最可能是n,在','以後不能有空格,不然會出錯,而且均爲閉區間。express
{n} 以前的元素必須出現n次
{m,n} 以前元素最少出現m次,最多n次
{m,} 以前的元素最少出現m次,無上限
{0,n} 以前的元素能夠不出現,也能夠出現,出現的話最多出現n次緩存
除了之上,還有三個經常使用的量詞*,?和+編輯器
* 等價於{0,}
+ 等價於{1,}
\? 等價於{0,1}函數
還有^和$,分別表示段或者字符串的開始與結束。工具
import re re.search("^travell?er$", "traveler") # True re.search("^travell?er$", "traveller") # True re.search("^ab\*", "abbbbbbb") # True,返回"abbbbbbb" re.search("^ab\*?", "abbbbbbb") # True,返回"a" re.search("^ab+", "abbbbbbb") # True,返回"abbbbbbb" re.search("^ab+?", "abbbbbbb") # True,返回"ab"