使用正则表达式从Python文本中提取第一个日期

时间:2018-09-27 15:31:03

标签: python regex

我正在使用以下正则表达式在每一行中查找第一个日期。

(?: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

1 个答案:

答案 0 :(得分:3)

您需要

  • 逐行读取文件
  • 使用re.search查找一行中的第一个匹配项
  • 如果有比赛(只有这样),请抓住比赛组#0。

类似

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仅在模式中定义了捕获组的情况下才返回捕获的文本。