如何通过regexp限制匹配数

2024-10-16 20:39:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串:

"It was in 1990. Then it was in 1992. Then it was in 2000. Then it was in 2005. Then it was in 2010."

我有以下regexp来匹配字符串中的年份:

\d{4}

它与弦中存在的所有年份相匹配。我想要的是将regexp限制为只有第一个匹配,这样它就只能给出'1990'。我在pytho中使用以下代码:

import re
s =  "It was in 1990. Then it was in 1992. Then it was in 2000. Then it was in 2005.      Then it was in 2010."
print re.findall(r"\d{4}", s)
['1990', '1992', '2000', '2005', '2010'] # output

我知道我可以通过添加[0]得到第一个,如下所示:

print re.findall(r"\d{4}", s)[0]
1990 # output

但我特别寻找正则表达式模式来获得这个输出。你知道吗


Tags: 字符串代码inimportreoutputitprint
3条回答

使用^{}

>>> import re
>>> s =  "It was in 1990. Then it was in 1992. Then it was in 2000. Then it was in 2005.      Then it was in 2010."
>>> re.search("\d{4}", s)
<_sre.SRE_Match object at 0x01939AA0>
>>> re.search("\d{4}", s).group()
'1990'
>>>

你可以用检索相反。它返回MatchObject或null。通过调用MatchObject上的组(0),可以从该对象获取匹配的文本。你知道吗

也可以使用re.finditer(r"\d{4}", s)

In [38]: import re

In [39]: s =  "It was in 1990. Then it was in 1992. Then it was in 2000. Then it was in 2005.      Then it was in 2010."

In [40]: ret = re.finditer(r"\d{4}", s)

In [41]: ret.next().group()
Out[41]: '1990'

相关问题 更多 >