我有以下字符串:
"It was in 1990. Then it was in 1992. Then it was in 2000. Then it was in 2005. Then it was in 2010."
我有以下正则表达式匹配字符串中的一年:
\d{4}
它匹配字符串中存在的所有年份。我想要的是将正则表达式限制为只有第一个匹配,所以它应该只给我'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
但我特意寻找正则表达式来获得此输出。
答案 0 :(得分:1)
使用re.search
:
>>> 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'
>>>
答案 1 :(得分:1)
您也可以使用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'
答案 2 :(得分:1)
您可以使用re.search代替。它返回一个MatchObject或null。你可以通过调用它上面的group(0)从MatchObject中获取匹配的文本。