歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python正則表達式:最短匹配

Python正則表達式:最短匹配

日期:2017/3/1 9:10:49   编辑:Linux編程

最短匹配應用於:假如有一段文本,你只想匹配最短的可能,而不是最長。

例子

比如有一段html片段,'\this is first label\\the second label\',如何匹配出每個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'(.*?)'的意圖是匹配被和包含的文本,但是正則表達式中*操作符是貪婪的,因此匹配操作會查找出最長的可能。
但是在*操作符後面加上?操作符,這樣使得匹配變成非貪婪模式,從而得到最短匹配。

Ubuntu 14.04安裝Python 3.3.5 http://www.linuxidc.com/Linux/2014-05/101481.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Copyright © Linux教程網 All Rights Reserved