簡體   English   中英

Powershell RegEx:如何將帶有兩個匹配字符串的行匹配?

[英]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]+)

這個正則表達式提供了您想要的所有組。

參見演示。

http://regex101.com/r/lK9iD2/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

您可以使用以下正則表達式:

^([\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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM