Powershell:match运算符返回true但$ matches为null

Mat*_*nig 39 regex powershell

我正在使用正则表达式来匹配文件内容:

> (get-content $_) -match $somePattern
the line of text that matches the pattern
Run Code Online (Sandbox Code Playgroud)

这返回true,匹配,但我的$ matches变量保持为null.

> $matches -eq $null
True
Run Code Online (Sandbox Code Playgroud)

$ match是否应该包含匹配组?

Rom*_*min 63

严格来说string -match ...,collection -match ...是两个不同的运营商.第一个获取布尔值并填充$matches.第二个获取与模式匹配的每个集合项,并且显然不填充$matches.

如果文件包含单行(第一个运算符工作),您的示例应该按预期工作.如果文件包含2+行,则使用第二个运算符$matches且未设置.

对于应用于集合的其他布尔运算符也是如此.那是collection -op ...返回where item -op ...为true的项.

例子:

1..10 -gt 5 # 6 7 8 9 10
'apple', 'banana', 'orange' -match 'e' # apple, orange 
Run Code Online (Sandbox Code Playgroud)

如果使用得当,应用于集合的布尔运算符很方便.但它们也可能令人困惑,并且容易犯错误:

$object = @(1, $null, 2, $null)

# "not safe" comparison with $null, perhaps a mistake
if ($object -eq $null) {
    '-eq gets @($null, $null) which is evaluated to $true by if!'
}

# safe comparison with $null
if ($null -eq $object) {
    'this is not called'
}
Run Code Online (Sandbox Code Playgroud)

另一个示例-match,并-notmatch可能看起来很奇怪:

$object = 'apple', 'banana', 'orange'

if ($object -match 'e') {
    'this is called'
}

if ($object -notmatch 'e') {
    'this is also called, because "banana" is evaluated to $true by if!'
}
Run Code Online (Sandbox Code Playgroud)

  • 非常彻底的回答,@罗曼!另一个观点(以及爱丽丝梦游仙境的转折!)感兴趣的读者也可以看看我的文章[利用PowerShell的字符串比较和列表过滤功能](http://www.simple-talk.com/dotnet/.在Simple-Talk.com上发布的net-tools/harnessing-powershells-string-comparison-and-list-filtering-features /).本文附有一个挂图,说明了标量和数组上下文中的`-match`运算符(和变量)以及许多其他运算符. (6认同)
  • 是的,就是这样。我的 get-content 返回一个数组,但最后一行不匹配,导致 $matches 清空。 (2认同)
  • `获取剪贴板` = 集合;`获取剪贴板-Raw` = 字符串。辛苦学习了...... (2认同)

Piy*_*oni 10

我有同样的问题,确切的行是从Powershell命令提示符,但不是从Powershell ISE或正常的命令提示符.如果你不想使用foreach逐个遍历文件的所有行,你可以简单地将它转换为这样的字符串,它应该工作:

if([string](Get-Content -path $filePath) -match $pattern)
{
   $matches[1]
}
Run Code Online (Sandbox Code Playgroud)