如何在python中使用正则表达式匹配特定的时间和日期

2024-04-25 05:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在解析日志文件,其中每一行都以日期、时间和系统事件消息开头。我想使用正则表达式来匹配所需的日期和时间,而不需要使用strtime或任何其他时间模块来进行计算。我试着匹配9月12日的日期和具体时间(9:23:45-09:23:50),即记录5秒。日志文件的格式如下:

Sep 12 09:23:45 localhost systemd: Switching root.
Sep 12 09:23:45 localhost journal: Journal stopped
Sep 12 09:23:46 localhost journal: Runtime journal is using 8.0M (max allowed 91.1M, trying to leave 136.7M free of 903.7M available ? current limit 91.1M).
Sep 12 09:23:46 localhost journal: Runtime journal is using 8.0M (max allowed 91.1M, trying to leave 136.7M free of 903.7M available ? current limit 91.1M).
Sep 12 09:23:46 localhost systemd-journald[88]: Received SIGTERM from PID 1 (systemd).

我尝试过的python代码:

import fileinput,re
for i in fileinput.input():
    if (re.search(r'Sep 12 09:23:[45-50]',i)):
        print(i)

另外,有谁能告诉我,如果我试图解析超过100gb的大文件,同样的代码会产生什么影响?我可以重写这段代码以减少内存开销吗?你知道吗


Tags: 文件to代码localhostis时间maxsep
1条回答
网友
1楼 · 发布于 2024-04-25 05:48:41

我会用一个稍微不同的正则表达式:

^Sep 12 09:23:(?:4[5-9]|50)

说明:[45-50]是一个字符类,它匹配4、介于55之间的所有内容以及0。这是因为character类是逐字符计算的。经典的解决方法是通过数字前缀定义备选方案:

  • (?:...)是一个非录制组,用于节省一些资源
  • 4[5-9]匹配数字4546。。。49
  • 另一种选择是50,即区间的上限。你知道吗

演示here。你知道吗

您可以确保只编译一次regex。因此,您的脚本使用更少的内存和CPU:

import fileinput,re
# this is the speedup
regex = re.compile('^Sep 12 09:23:(?:4[5-9]|50)')
for i in fileinput.input():
    # slightly different regex match call
    if (regex.match(i)):
        print(i)

相关问题 更多 >