最短匹配應用於:假如有一段文本,你只想匹配最短的可能,而不是最長。
例子
比如有一段html片段,'<a>this is first label</a><a>the second label</a>',如何匹配出每個a標簽中的內容,下面來看下最短與最長的區別。
代碼
>>> import re
>>> str = '<a>this is first label</a><a>the second label</a>'
>>> print re.findall(r'<a>(.*?)</a>', str) # 最短匹配
['this is first label', 'the second label']
>>> print re.findall(r'<a>(.*)</a>', str)
['this is first label</a><a>the second label']
解釋
例子中,模式r'(.*?)'的意圖是匹配被和包含的文本,但是正則表達式中*操作符是貪婪的,因此匹配操作會查找出最長的可能。
但是在*操作符后面加上?操作符,這樣使得匹配變成非貪婪模式,從而得到最短匹配。
