Regex Powershell正则表达式:如何使用两个匹配字符串匹配行?
我试图从文本日志文件中提取某些数据片段,并将这些数据保存到输出文件中。 文本文件中的数据如下所示:Regex Powershell正则表达式:如何使用两个匹配字符串匹配行?,regex,powershell,Regex,Powershell,我试图从文本日志文件中提取某些数据片段,并将这些数据保存到输出文件中。 文本文件中的数据如下所示: 2014-08-23 19:05:09 <nonmatching line> 2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 1 2 3' <more_stuff_I_don't_want_to_EOL> 2014-08-23 19:05:09 &l
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 1 2 3' <more_stuff_I_don't_want_to_EOL>
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 4 5 6' <more_stuff_I_don't_want_to_EOL>
2014-08-23 19:05:09 12345 queue1 1 2 3
2014-08-23 19:05:09 12345 queue1 4 5 6
^([\d-:\s]{2,}).*?(?<==)'(\d+)(.+?)'
我有两个正则表达式用于两个必要的匹配项,当它们单独使用时,它们都可以工作,如下所示:
(^.*?)(?=\b\tMATCH_STRING\b)
返回
2014-08-23 19:05:09
2014-08-23 19:05:09
12345 queue1 1 2 3
12345 queue1 4 5 6
及
问题是:
如何将它们放在一起,使它们既匹配行首的日期,又匹配行中引用的字符串
额外问题:对于我正在尝试做的事情,是否有更有效的正则表达式
谢谢
这个正则表达式提供您想要的所有组
见演示
另一个解决方案:
$matchstring = "MATCH_STRING"
$pattern = "(.*?)(?:\s*?$([regex]::Escape($matchstring)).*?description=')(.*?)'.*"
@"
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 1 2 3' <more_stuff_I_don't_want_to_EOL>
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 4 5 6' <more_stuff_I_don't_want_to_EOL
"@ -split [environment]::newline |
Where-Object { $_ -match $pattern } |
ForEach-Object { $_ -replace $pattern, '$1 $2' }
2014-08-23 19:05:09 12345 queue1 1 2 3
2014-08-23 19:05:09 12345 queue1 4 5 6
您可以使用这样的正则表达式:
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 1 2 3' <more_stuff_I_don't_want_to_EOL>
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 4 5 6' <more_stuff_I_don't_want_to_EOL>
2014-08-23 19:05:09 12345 queue1 1 2 3
2014-08-23 19:05:09 12345 queue1 4 5 6
^([\d-:\s]{2,}).*?(?<==)'(\d+)(.+?)'