2014-08-28 131 views
0

我试图从文本日志文件中拉出某些数据并将该数据保存到输出文件。 在文本文件中的数据是这样的:Powershell RegEx:如何将两行匹配的字符串匹配?

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 

我和2个需要匹配两个正则表达式的表达式时他们2单独使用,它们都工作,如下图所示:

(^.*?)(?=\b\tMATCH_STRING\b) 

回报

2014-08-23 19:05:09 
2014-08-23 19:05:09 

(?<[email protected]\=')(?:(?!').)* 

回报

12345 queue1 1 2 3 
12345 queue1 4 5 6 

的问题是: 我如何把它们放在一起,使它们匹配在该行的开始日期和在引用的字符串线?

红利问题:我正在尝试做什么更有效的RegEx?

感谢

回答

0

另一种解决方案:

$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 
0

您可以使用正则表达式是这样的:

^([\d-:\s]{2,}).*?(?<==)'(\d+)(.+?)' 

Working demo

enter image description here

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`