首页 > 解决方案 > 使用普通正则表达式查找重叠匹配

问题描述

我正在使用以下正则表达式在服务器日志文件中查找应用程序的 Start-Stop-Blocks:

\[\d{2}\.\d{2}\.\d{2}\s\d{2}\:\d{2}\:\d{2}\:\d{1,3}\sMET\].+The Application\s([a-zA-Z0-9]*)\sis starting\.[\s\S]*\[\d{2}\.\d{2}\.\d{2}\s\d{2}\:\d{2}\:\d{2}\:\d{1,3}\sMET\].+The Application started:\s\1

服务器日志格式如下所示:

[10.12.19 15:29:10:408 MET] 0000006a ApplicationMg A  WSVR0200I: The Application query is starting.
[10.12.19 15:29:11:102 MET] 0000006a CompositionUn A  WSVR0191I: Composition unit AB started
[10.12.19 15:29:11:222 MET] 0000006a CompositionUn A  WSVR0191I: Composition unit CD started
[10.12.19 15:29:11:412 MET] 0000006a ApplicationMg A  WSVR0200I: The Application tracer is starting.
[10.12.19 15:29:12:108 MET] 0000006a CompositionUn A  WSVR0191I: Composition unit DE started.
[10.12.19 15:29:12:541 MET] 0000006a ApplicationMg A  WSVR0200I: The Application started: query
[10.12.19 15:29:13:417 MET] 0000006a ApplicationMg A  WSVR0200I: The Application started: tracer

[10.12.19 15:30:12:145 MET] 0000006a ApplicationMg A  WSVR0200I: The Application test is starting.
[10.12.19 15:30:13:408 MET] 0000006a CompositionUn A  WSVR0191I: Composition unit XY started.
[10.12.19 15:30:14:678 MET] 0000006a ApplicationMg A  WSVR0200I: The Application started: test

此服务器日志中有三个应用程序:查询、跟踪器和测试。该表达式将产生两个匹配项:查询的开始-停止日志(第 1-6 行)和测试(第 9-11 行)。但它与嵌套的 tracer-app-logs 不匹配(第 4-7 行)。

是否可以使用正则表达式捕获嵌套/重叠匹配?

正则表达式101.com

标签: regex

解决方案


感谢@jhnc,我能够使用积极的前瞻来找到解决方案:

(?=(\[\d{2}\.\d{2}\.\d{2}\s\d{2}\:\d{2}\:\d{2}\:\d{1,3}\sMET\].+The Application\s([a-zA-Z0-9]*)\sis starting\.[\s\S]*\[\d{2}\.\d{2}\.\d{2}\s\d{2}\:\d{2}\:\d{2}\:\d{1,3}\sMET\].+The Application started:\s\2))

另请参阅以下正则表达式示例:https ://regex101.com/r/XuFLPm/4


推荐阅读