首页 / 操作系统 / Linux / Python正则表达式:最短匹配
最短匹配应用于:假如有一段文本,你只想匹配最短的可能,而不是最长。
例子
比如有一段html片段," his 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.htmCentOS上源码安装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.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-10/136298.htm