【发布时间】:2014-04-20 17:14:54
【问题描述】:
我需要 limit re.findall 来查找前 3 个匹配项,然后停止。
例如
text = 'some1 text2 bla3 regex4 python5'
re.findall(r'\d',text)
然后我得到:
['1', '2', '3', '4', '5']
我想要:
['1', '2', '3']
【问题讨论】:
我需要 limit re.findall 来查找前 3 个匹配项,然后停止。
例如
text = 'some1 text2 bla3 regex4 python5'
re.findall(r'\d',text)
然后我得到:
['1', '2', '3', '4', '5']
我想要:
['1', '2', '3']
【问题讨论】:
re.findall 返回一个列表,所以最简单的解决方案就是使用slicing:
>>> import re
>>> text = 'some1 text2 bla3 regex4 python5'
>>> re.findall(r'\d', text)[:3] # Get the first 3 items
['1', '2', '3']
>>>
【讨论】:
要找到 N 个匹配项并停止,您可以使用 re.finditer 和 itertools.islice:
>>> import itertools as IT
>>> [item.group() for item in IT.islice(re.finditer(r'\d', text), 3)]
['1', '2', '3']
【讨论】: