[英]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.