我正在尝试编写一个正则表达式,它将从日志文件返回多行匹配。使用下面的示例——我想匹配整个“事务”,其开头和结尾与日志中所有其他事务(开始和结束)的文本相同。然而,在这些行之间有一个自定义标识符,在本例中是一个电子邮件地址,可以将一笔交易与另一笔交易区分开来。
Start of a transaction.
random line 1.
random line 2.
[email protected] /cdn-cgi/l/email-protection
End of a transaction.
Start of a transaction.
random line 1.
random line 2.
[email protected] /cdn-cgi/l/email-protection
random line 3.
End of a transaction.
这是我要开始的内容:
^Start(.*?)\n(((.*?)(email1\@gmail\.com)(.*?)|(.*?))\n){1,}End (.*?)\n
本质上 - 我想说:从“开始”开始 - 匹配所有行直到“结束”行,但仅当其中一行包含特定电子邮件地址时才返回匹配项。
现在——我的正则表达式将整个日志文件视为单个匹配,因为大概第 1 行包含“开始”,第 X 行包含“结束”以及中间数百行中的某个地方——它们与电子邮件匹配。另外——应用程序是 Powershell,并且将使用 Select-String 模式(如果有的话)。
Use a 否定前瞻断言 http://www.regular-expressions.info/lookaround.html确保您的正则表达式永远不会跨越“事务结束”边界匹配:
preg_match_all(
'/^ # Start of line
Start\ of\ a\ transaction\. # Match starting tag.
(?: # Start capturing group.
(?!End\ of\ a\ transaction) # Only match if we\'re not at the end of a tag.
. # Match any character
)* # any number of times.
email1@gmail\.com # Match the required email address
(?:(?!End\ of\ a\ transaction).)* # and the rest of the tag.
^ # Then match (at the start of a line)
End\ of\ a\ transaction\.\n # the closing tag./smx',
$subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];
Test it 住在 regex101.com https://regex101.com/r/qB5rH2/1.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)