简体   繁体   English

Powershell RegEx:如何将带有两个匹配字符串的行匹配?

[英]Powershell RegEx: How can I match lines with two matching strings?

I am trying to pull certain pieces of data from a text log file and save that data to an output file. 我试图从文本日志文件中提取某些数据并将其保存到输出文件。 The data in the text file looks like this: 文本文件中的数据如下所示:

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>

I want to create an out put file that looks like this: 我想创建一个如下所示的输出文件:

2014-08-23 19:05:09 12345 queue1 1 2 3
2014-08-23 19:05:09 12345 queue1 4 5 6

I have two RegEx expressions for the 2 necessary matches and when they are used seperately, they both work, as below: 对于两个必需的匹配项,我有两个RegEx表达式,当分别使用它们时,它们都可以正常工作,如下所示:

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

returns 退货

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

and

(?<=@description\=')(?:(?!').)*

returns 退货

12345 queue1 1 2 3
12345 queue1 4 5 6

The question is: How do I put them together so that they match both date at the beginning of the line and the quoted string in the line? 问题是:如何将它们放在一起,以便它们与行开头的日期和行中带引号的字符串都匹配?

Bonus question: Is there more efficient RegEx for what I am trying to do? 额外的问题:我要执行的操作是否有更有效的RegEx?

Thanks 谢谢

(\d+-\d+-\d+\s*\d+:\d+:\d+).*?(?=@description).*?=.(\d+)\s*(.*?[\d\s]+)

This regex gives all the groups you want. 这个正则表达式提供了您想要的所有组。

See Demo. 参见演示。

http://regex101.com/r/lK9iD2/6 http://regex101.com/r/lK9iD2/6

Another solution: 另一个解决方案:

$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

You can use a regex like this: 您可以使用以下正则表达式:

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

Working demo 工作演示

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM