【发布时间】:2019-02-09 04:25:39
【问题描述】:
我想使用 .NET / Powershell 正则表达式在日志中搜索特定位置的 Success 状态,例如 ABC。
如果我使用以下模式:"(?ms)A status: Success.*?Location: " 和全局(又名 AllMatches),那么它会在任何位置找到状态为 Success 的所有日志记录。
如果我尝试通过将ABC 附加到模式来缩小范围,那么匹配太贪心了,从第 18 行的 Success 一直到第 28 行的 ABC。
我放弃并使用了更明确的模式(它获取完整的日志记录并且似乎可以工作,因为我在 Success 和 Location 之间指定了一个模式):
(?sm)^\d([ \S]*\s{10}){3}A status: Success\s{2}([ \S]*\s{10}){2}Location: ABC[ \S]*
有没有更简单的模式可以找到我想要的东西?
注意:我不介意模式是否抓取从日期时间(含)到日期时间(不含)的完整日志记录,
日志文件:
04/09/2018 06:31:59 AM [class | Info] some message received from 101592 (123.123.123.124)
Request Id: 0 (Descriptor: 0, Operator Request Id: 0)
A type: bar
A status: Queued
The id: 1E25
Additional info: Inserted in queue at position 1 on device ABC
Location: ABC, subarea: 2
04/09/2018 06:31:59 AM [class | Info] some message received from 102364 (123.123.123.123)
Request Id: 0 (Descriptor: 0, Operator Request Id: 0)
A type: bar
A status: Queued
The id: 1E25
Additional info: Inserted in queue at position 1 on device ABC
Location: ABC, subarea: 2
04/09/2018 06:31:59 AM [class | Info] some message received from 102364 (123.123.123.123)
Request Id: 0 (Descriptor: 0, Operator Request Id: 0)
A type: blah bit foo
A status: Success
The id: T908
Additional info:
Location: DEF, subarea: 3
04/09/2018 06:32:00 AM [class | Info] some message received from 102364 (123.123.123.123)
Request Id: 0 (Descriptor: 0, Operator Request Id: 0)
A type: bar
A status: Success
The id: DG08
Additional info:
Location: ABC, subarea: 1
【问题讨论】:
-
single regex 方法在这里相当麻烦。
-
使用
Get-Content -Raw读取文件,在"(?m)^(?=\d{2}/\d{2}/\d{4})"分割成块,并反复使用Where-Object或Select-String过滤你想要的块。
标签: .net regex powershell