我正在使用以下正则表达式在每一行中查找第一个日期。
(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{2}:\d{2}:\d{2}\s\d{4}
这是可行的,但它匹配所有日期。但是,我只需要每行的第一个日期为“ Feb 19 22:25:19 2018”。
示例文本文件
Mon Feb 19 22:25:19 2018 ABC.ls:9999: some text here, Mon Feb 19 22:25:19 2017\n
Mon Feb 19 22:25:20 2018 ABC.ls:9999: some text here\n
Mon Feb 19 22:25:20 2018 ABC.ls:9999: some text here, () with some more text\n
TIA
答案 0 :(得分:3)
您需要
re.search
查找一行中的第一个匹配项类似
import re
rx = re.compile(r'(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{2}:\d{2}:\d{2}\s\d{4}')
res = []
with open(file, "r") as f:
for line in f:
m = rx.search(line)
if m:
res.append(m.group())
请参见Python demo:
import re
file = """Mon Feb 19 22:25:19 2018 ABC.ls:9999: some text here, Mon Feb 19 22:25:19 2017
Mon Feb 19 22:25:20 2018 ABC.ls:9999: some text here
Mon Feb 19 22:25:20 2018 ABC.ls:9999: some text here, () with some more text"""
rx = re.compile(r'(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{2}:\d{2}:\d{2}\s\d{4}')
res = []
for s in file.splitlines():
m = rx.search(s)
if m:
res.append(m.group())
print(res)
# => ['Feb 19 22:25:19 2018', 'Feb 19 22:25:20 2018', 'Feb 19 22:25:20 2018']
由于您希望将整个文件读入内存并通过一次调用re.findall
来获取所有必要的匹配项,因此可以使用
re.findall(r'(?m)^.*?((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{2}:\d{2}:\d{2}\s\d{4})', file_contents)
请参见regex demo
正则表达式为(?m)^.*?(...)
形式,与之匹配
(?m)
-re.M
/ re.MULTILINE
模式已启用,以使^
与行首匹配^
-一行的开头.*?
-除换行符以外的任何0+个字符,并且尽可能少(...)
-一个捕获组,它将捕获您的日期时间模式,并且re.findall
仅在模式中定义了捕获组的情况下才返回捕获的文本。