本章的內容主要是為講解在正則表達式中常用的.*?和re.S!
在正則表達式中有貪婪匹配和最小匹配:如下為貪婪匹配(.*)
1 import re 2 match = re.search(r'PY.*', 'PYANBNCNDN') 3 print(match.group(0))
如上的代碼顯示的結果是PYANBNCNDA,為貪婪匹配,會把整個字符串進行匹配,把能夠滿足條件的子串提取出來!
如下為最小匹配:(.*?)
1 import re 2 match = re.search(r'PY.*?N', 'PYANBNCNDN') 3 print(match.group(0))
如上的代碼顯示的結果是PYAN,為最小匹配,會從頭開始匹配,當匹配到滿足條件時,不會再去匹配!
re.S
在python的正則表達式中,有一個參數re.S。它表示“.”的作用擴展到整個字符串,包括“\n”。
1 a = ''' 2 asdfhellopass: 3 worldaf 4 ''' 5 6 b = re.findall('hello(.*?)world', a) 7 c = re.findall('hello(.*?)world', a, re.S) 8 print(b) 9 print(c) 10 11 12 [] 13 ['pass:\n ']
拓展:
