Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 正則表達式:掌握最短匹配的用法

最短匹配適用於這樣的情境:當你面對一段文字,只想擷取最短的可能結果,而非最長的那個。

例子

舉個例子,假設有一段 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'(.*?)' 的意圖是匹配被 <a> 與 </a> 包住的文字。然而正則表達式裡的 * 運算子天生是「貪婪」的,因此預設會找出最長的可能匹配。只要在 * 後面加上 ? 運算子,就能把匹配切換成非貪婪模式,從而取得最短的結果。

延伸閱讀:

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

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

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

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

Python 腳本獲取 Linux 系統資訊 https://www.linuxidc.com/Linux/2013-08/88531.htm

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

Copyright © Linux教程網 All Rights Reserved