[英]Powershell RegEx: How can I match lines with two matching strings?
我试图从文本日志文件中提取某些数据并将其保存到输出文件。 文本文件中的数据如下所示:
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
对于两个必需的匹配项,我有两个RegEx表达式,当分别使用它们时,它们都可以正常工作,如下所示:
(^.*?)(?=\b\tMATCH_STRING\b)
退货
2014-08-23 19:05:09
2014-08-23 19:05:09
和
(?<=@description\=')(?:(?!').)*
退货
12345 queue1 1 2 3
12345 queue1 4 5 6
问题是:如何将它们放在一起,以便它们与行开头的日期和行中带引号的字符串都匹配?
额外的问题:我要执行的操作是否有更有效的RegEx?
谢谢
(\d+-\d+-\d+\s*\d+:\d+:\d+).*?(?=@description).*?=.(\d+)\s*(.*?[\d\s]+)
这个正则表达式提供了您想要的所有组。
参见演示。
另一个解决方案:
$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
您可以使用以下正则表达式:
^([\d-:\s]{2,}).*?(?<==)'(\d+)(.+?)'
MATCH 1
1. [39-59] `2014-08-23 19:05:09 `
2. [107-112] `12345`
3. [112-125] ` queue1 1 2 3`
MATCH 2
1. [238-258] `2014-08-23 19:05:09 `
2. [306-311] `12345`
3. [311-324] ` queue1 4 5 6`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.