我一直在使用正則表達式來解析某些XML節點中的文本。但是,當我使用-SimpleMatch
與Select-String
時,MatchInfo對象似乎不包含任何匹配項。使用-SimpleMatch和選擇字符串時未捕獲匹配
我在網上找不到任何東西,表明這種行爲是正常的。我現在想知道它是否是我的Powershell安裝。
PS H:\> $c = "abd 14e 568" | Select-String -Pattern "ab"
PS H:\> $c.Matches
Groups : {ab}
Success : True
Captures : {ab}
Index : 0
Length : 2
Value : ab
但加入-SimpleMatch
:(供參考:我使用的電腦安裝了PowerShell 3.0)
用一個很簡單的例子,我們可以使用正則表達式時,圖案返回預期MatchInfo對象參數出現在MatchInfo對象不返回匹配屬性:
PS H:\> $c = "abd 14e 568" | Select-String -Pattern "ab" -SimpleMatch
PS H:\> $c.Matches
PS H:\>
管道$c
到Get-Member
印證返回一個MatchInfo對象:
PS H:\> $c | gm
TypeName: Microsoft.PowerShell.Commands.MatchInfo
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
RelativePath Method string RelativePath(string directory)
ToString Method string ToString(), string ToString(string directory)
Context Property Microsoft.PowerShell.Commands.MatchInfoContext Context {get;set;}
Filename Property string Filename {get;}
IgnoreCase Property bool IgnoreCase {get;set;}
Line Property string Line {get;set;}
LineNumber Property int LineNumber {get;set;}
Matches Property System.Text.RegularExpressions.Match[] Matches {get;set;}
Path Property string Path {get;set;}
Pattern Property string Pattern {get;set;}
等性能,如模式和線路工作:
PS H:\> $c.Pattern
ab
PS H:\> $c.Line
abd 14e 568
此外,發送的索引值的匹配陣列時不生成錯誤:
PS H:\> $c.Matches[0]
PS H:\>
我不確定如何解釋結果,我也不確定它發生的原因。
這種行爲是有問題的,因爲有很多次我必須搜索包含正則表達式特殊字符的字符串,()的很常見。
擴大的例子:
PS H:\> $c = "ab(d) 14e 568" | Select-String -Pattern "ab(d)"
PS H:\> $c.Matches
PS H:\>
$c.Matches
回報什麼,$c
本身是空,由於正則表達式中使用括號:
PS H:\> $c -eq $null
True
使用-SimpleMatch
不會產生MatchInfo對象,但仍不會返回任何匹配項:
PS H:\> $c = "ab(d) 14e 568" | Select-String -Pattern "ab(d)" -SimpleMatch
PS H:\> $c -eq $null
False
PS H:\> $c.Matches
PS H:\>
我發現(這裏SO)的解決方法是從.NET使用Regex.Escape方法:
(參考:Powershell select-string fails due to escape sequence)
PS H:\> $pattern = "ab(d)"
$pattern = ([regex]::Escape($pattern))
$c = "ab(d) 14e 568" | Select-String -Pattern $pattern
PS H:\> $c.Matches
Groups : {ab(d)}
Success : True
Captures : {ab(d)}
Index : 0
Length : 5
Value : ab(d)
作爲這種解決方法返回來自Select-String
預期匹配,我已經能夠繼續我的腳本。
但我很好奇爲什麼在使用-SimpleMatch
參數時沒有返回匹配項。
...
與問候,
Schwert酒店
'System.Text.RegularExpressions.Match'是常規的表達式對象,所以如果你不使用正則表達式,那麼你不會得到'Match'對象。 – PetSerAl
@PetSerAl:在此之前,我沒有將'Matches'對象傳遞給'Get-Member'。這樣做確實將'System.Text.RegularExpressions.Match'指示爲類型名稱。 –