Python正则表达式:最短匹配-演道网

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

例子

比如有一段html片段,’\this is first label\\the second label\‘,如何匹配出每个a标签中的内容,下面来看下最短与最长的区别。

代码

>>> import re
>>> str = 'this is first labelthe second label'

>>> print re.findall(r'(.*?)', str)  # 最短匹配
['this is first label', 'the second label']

>>> print re.findall(r'(.*)', str)
['this is first labelthe 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

转载自演道,想查看更及时的互联网产品技术热点文章请点击http://go2live.cn