【发布时间】:2015-10-16 21:20:50
【问题描述】:
我一直在使用正则表达式来解析一些 XML 节点中的文本。但是,当我使用 -SimpleMatch 和 Select-String 时,MatchInfo 对象似乎不包含任何匹配项。
我无法在网上找到任何表明此行为正常的信息。我现在想知道这是否是我的 Powershell 安装。 (供参考:我使用的计算机已安装 Powershell 3.0。)
使用一个非常简单的示例,我们可以在使用正则表达式模式时返回预期的 MatchInfo 对象:
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 参数似乎不会返回 MatchInfo 对象中的 Matches 属性:
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;}
还有其他属性,比如 Pattern 和 Line work:
PS H:\> $c.Pattern
ab
PS H:\> $c.Line
abd 14e 568
另外,将索引值发送到 Matches 数组时不会产生错误:
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 参数时没有返回匹配项。
...
关于,
施韦特
【问题讨论】:
-
System.Text.RegularExpressions.Match是正则表达式对象,所以如果不使用正则表达式,则不会得到Match对象。 -
@PetSerAl:我之前没有将
Matches对象通过管道传输到Get-Member。这样做确实会将System.Text.RegularExpressions.Match指示为类型名。
标签: regex powershell escaping select-string