python 正则表达式 非贪婪匹配问题 python中如何使用正则表达式的非贪婪模式示例

Python \u6b63\u5219\u8868\u8fbe\u5f0f \u975e\u8d2a\u5a6a\u5339\u914d\u95ee\u9898

\u7b2c\u4e8c\u6355\u83b7\u62ec\u53f7\u91cc\u9762\u662f (0*) \u2014\u20140\u4e2a\u6216\u591a\u4e2a0\uff0c \u540e\u9762\u63a5\u7740\u662f$\u2014\u2014\u884c\u5c3e,
02300\u2014\u2014\u4e0d\u6ee1\u8db3\u591a\u4e2a0.

\u6b63\u5219\u8868\u8fbe\u5f0f\u6539\u4e3a\uff1a
^(\d+?)(0.*)$
\u7ed3\u679c\u5c31\u4f1a\u662f\uff1a
("1", "02300")

import restr='abcdxyzsd1232abc'regex_greed='a.*d' # \u8d2a\u5a6a\u6a21\u5f0f\uff0ca\u5f00\u5934\u627e\u5230\u6700\u540e\u7684\u4e00\u4e2ad\u624d\u7ed3\u675fmatch_greed=re.match(regex_greed,str)print match_greed.group() # \u5339\u914d\u7ed3\u679c\uff1aabcdxyzsdregex_not_greed='a.*?d' # \u975e\u8d2a\u5a6a\u6a21\u5f0f\uff0ca\u5f00\u5934\u627e\u5230\u7b2c\u4e00\u4e2ad\u5c31\u7ed3\u675fmatch_not_greed=re.match(regex_not_greed,str)print match_not_greed.group() # \u5339\u914d\u7ed3\u679c\uff1aabcd

tim@tim-1215B:~$ python
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> data = 'Thu Feb 15 17:46:04 2007::[email protected]:: 2341123-6-8'
>>> patt = re.compile(r'.+(\d+-\d-\d)', re.X)
>>> print patt.match(data).group(1)
3-6-8
>>> patt = re.compile(r'.+?(\d+-\d-\d)', re.X)
>>> print patt.match(data).group(1)
2341123-6-8
>>>

因为group(1)对应的是(\d-\d-\d+),当然就是3-6-8咯。其实,为什么要用非得用正则表达式呢?用split不是很好吗?
data = 'Thu Feb 15 17:46:04 2007::[email protected]:: 2341123-6-8'
print data.split(':')[-1].split()[0] #第二个split是问了去掉“:”和数字之间的那个空格
结果为2341123-6-8。:)

多个数字要用\d+

扩展阅读:学了python再学c++好学吗 ... 正则表达式在线生成器 ... 正则表达式python心得 ... 正则 python 爬小说 ... python正则表达式compile ... 20个常用的正则表达式 ... python写数学表达式 ... python表达式的书写规则 ... 正则表达式python匹配数字 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网