[英]how to multi line regex match each distinct entry of a log file
对于日志文件,我试图为每个不同的条目获取匹配,即使它跨越多行。 即使有多行与该条目相关,每个不同的条目都将以时间戳开头。
这是我的日志文件:
2000-01-01 01:01:01 UTC This is a 2 line sentence.
This is the second line
2000-01-01 01:01:02 UTC some random text on 1 line
2000-01-01 01:01:03 UTC This is a much longer 1 line sentence that manages to wrap itself around because of its length
2022-01-01 01:01:04 UTC This multi line paragraph has a few blank lines in between lines of text
words words words and some numbers12345
a few more words
more words on another line and the next line might be blank
2000-01-01 01:01:05 UTC some random text on 1 line
2000-01-01 06:01:06 UTC This multi line paragraph has a few blank lines in between lines of text
words words words and some numbers678910
a few more words
more words on another line and the next line might be blank
2000-01-01 01:01:07 UTC some random text on one line
我试图基本上匹配任何不以时间戳开头的行。
这可以很好地作为基础,但它不会抓取任何跨越多行的条目:
^([0-9]{4}[-][0-9]{2}[-][0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} UTC [[][0-9]+[]]: [[][0-9]+[-][0-9]+[]].+\n)
我已经尝试添加到它来做一个否定的前瞻来尝试让每个不同的条目像这样匹配,但这是不对的,我得到的匹配更少: ^([0-9]{4}[-][0-9]{2}[-][0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} UTC.+\n)(.+\n)*(?:([0-9]{4}[-][0-9]{2}[-][0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} UTC))
有没有办法构建一个正则表达式来获取每个不同的条目?
您的第一个示例似乎考虑了毫秒,我在您的日志中没有看到。
你可以做一个积极的前瞻:
^([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} UTC) (.*?)(?=[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}|\z)
它会抓取日志文本,直到遇到另一个时间戳或输入结束( \z
),然后分别捕获时间戳和日志条目。
从您的第一个正则表达式开始,我不明白您为什么使用[[][0-9]+[]]: [[][0-9]+[-][0-9]+[]].+\n
UTC
之后的[[][0-9]+[]]: [[][0-9]+[-][0-9]+[]].+\n
以及[.][0-9]+
应该有什么好处。
但是,这就是您如何使其与 Negative Lookahead 一起使用的方法:
^(?![0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} UTC).*
因此它将忽略以时间戳开头的行,直到UTC
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.