我有以下字符串:
"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
但我特别寻找正则表达式模式来获得这个输出。你知道吗
使用^{} :
你可以用检索相反。它返回MatchObject或null。通过调用MatchObject上的组(0),可以从该对象获取匹配的文本。你知道吗
也可以使用
re.finditer(r"\d{4}", s)
相关问题 更多 >
编程相关推荐