[英]PowerShell -match operator and multiple groups
我有以下日志條目,我正在 PowerShell 中處理我正在嘗試使用-match
運算符提取所有活動名稱和持續時間,但我只得到一個匹配組。 當我使用Regex
對象在 C# 中做同樣的事情時,我沒有得到我看到的所有匹配。 有人可以解釋我做錯了什么嗎?
相關的 PowerShell 腳本
$formattedMessage -match "(Get\sClient\sModel|Parse\sExpression|Get\sAbstract\sQuery|Compile\sQuery|Execute\sQuery|Get\sQuery\sPlan\sComplexity|Async\sTotal|Total)\s-\sduration\(([0-9]*)" | out-null
$matches
輸出
Name Value
---- -----
0 Get Client Model - duration(0
1 Get Client Model
2 0
日志條目示例:
Timestamp: 11/9/2009 6:48:41 PM
Message:
Category: QueryService
Priority: 3
EventId: 1001
Severity: Information
Title: SPARQL Query Response
Machine: SPOON16-SERVER
App Domain: KnowledgeBaseHost.exe
ProcessId: 2040
Process Name: D:\QueryService\QSHost.exe
Thread Name:
Win32 ThreadId:8092
Extended Properties:
Key - Workflow_cbbdd58b-e574-4054-88d4-1dd7a56dc9d9
Timeout - 1800
Result Format - WireTable
Result from Registry - False
Compiled Query from Cache - True
Result Count - 28332
Query Plan Complexity - 661622
Get Client Model - duration(0) start(0)
Parse Expression - duration(0) start(0)
Get Abstract Query - duration(0) start(0)
Compile Query - duration(0) start(0)
Get Query Plan - duration(0) start(1)
Execute Query - duration(63695) start(1)
Get Query Plan Complexity - duration(0) start(63696)
Get Executed Operations - duration(0) start(63696)
Total - duration(63696) start(0)
Async Total - duration(63696) start(0)
我能夠通過定義一個正則表達式然后在該正則表達式上調用.Matches來獲取所有組。 我仍然很想知道這是否可以使用 PowerShell 中的-match運算符來完成。
$detailRegex = [regex]"(Get\sClient\sModel|Parse\sExpression|Get\sAbstract\sQuery|Compile\sQuery|Execute\sQuery|Get\sQuery\sPlan\sComplexity|Async\sTotal|Total)\s-\sduration\(([0-9]*)"
$detailRegex.Matches($formattedMessage)
您可以使用 V2 中的Select-String cmdlet 執行此操作,但您需要指定-AllMatches開關,例如:
$formattedMessage | Select-String 'regexpattern' -AllMatches
請記住,使用-match
運算符,您所做的主要事情是尋找“a”匹配,即正則表達式模式是否匹配?
-match 操作符只能使用一次; 它不會對輸入進行全局匹配。 Keith Hill 在此處為Microsoft Connect上的-matchall操作員提出了建議。
我會建議另一種方法來做到這一點。 如果日志條目在文件中,您可以使用 switch 語句來完成同樣的事情:
switch -regex -file .\log.txt { $entryRegex { $matches[1] + ", " + $matches[2] } }
如果$entryRegex
具有您定義的正則表達式,則這是我使用此語句獲得的輸出:
Get Client Model, 0
Parse Expression, 0
Get Abstract Query, 0
Compile Query, 0
Execute Query, 63695
Get Query Plan Complexity, 0
Total, 63696
Async Total, 63696
http://www.johndcook.com/regex.html給出了一個不錯的例子
而且,無論如何,簡化你的表達:
^([^-]+)\s*-\s*duration\(([0-9]+)
您可以在表達式中包含正則表達式選項,但遺憾的是,全局似乎不是可用選項之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.