未找到使用Python正则表达式“:”字符分析时间戳

2024-06-03 02:04:08 发布

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

我在自学python,并尝试实现正则表达式以从应用程序日志文件中获取时间戳(为此,我通常使用grepcutawk

我的日志文件包含许多以日期和时间开始的行

18.12.19 14:03:16 [ ..... # message error
18.12.19 14:03:16 [
:

我通常使用一个简单的grep命令grep "14\:03\:16" mytext 这个表达式的作用是“14:03:16”,所以经过研究,我想出了这个正则表达式:

其中res是上面的一行

datap = re.compile(r'(\d{2}):(\d{2}):(\d{2})')
m = datap.match(res)

这没有发现任何东西

datap = re.compile(r'(\d{2}).(\d{2}).(\d{2})')
m = datap.match(re

捕获日期。你知道吗

为什么找不到字符:?我也尝试过使用\:,但也不起作用。提前谢谢。你知道吗


Tags: 文件命令re应用程序messagematch时间res
1条回答
网友
1楼 · 发布于 2024-06-03 02:04:08

^{}尝试从字符串开头匹配正则表达式。你知道吗

从文档中:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

当你这么做的时候

datap = re.compile(r'(\d{2}).(\d{2}).(\d{2})')
m = datap.match(res)

正则表达式实际上匹配的是日期,而不是时间(因为它位于字符串的开头):

print(m)
# <re.Match object; span=(0, 8), match='18.12.19'>

如果使用^{},则会得到预期的输出:

import re

res = '18.12.19 14:03:16 [ ..... # message error'
datap = re.compile(r'(\d{2}):(\d{2}):(\d{2})')
m = datap.search(res)
print(m)
# <re.Match object; span=(9, 17), match='14:03:16'>

相关问题 更多 >