例如,我有一串时间:
text = '2010; 04/20/2010; 04/2009'
我只想找到第一个独立的“2010”,但应用以下代码:
re.findall(r'\d{4}', text)
还会发现以 mm/dd/yyyy 格式嵌入的第二个“2010”。
有没有办法实现这一点(不使用“;”符号)?
最佳答案
您可以使用re.search
仅查找第一个出现的位置:
>>> import re
>>> text = '2010; 04/20/2010; 04/2009'
>>> re.search('\d{4}', text)
<_sre.SRE_Match object; span=(0, 4), match='2010'>
>>> re.search('\d{4}', text).group()
'2010'
>>>
来自文档:
re.search(pattern, string, flags=0)
Scan through
string
looking for the first location where the regular expressionpattern
produces a match, and return a corresponding match object. ReturnNone
if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
强调我的。
关于Python正则表达式查找独立案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45517690/