【问题标题】:Powershell: match operator returns true but $matches is nullPowershell:匹配运算符返回true,但$matches为空
【发布时间】:2012-01-28 22:18:43
【问题描述】:

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

> (get-content $_) -match $somePattern
the line of text that matches the pattern

这返回 true,匹配,但是我的 $matches 变量仍然为空。

> $matches -eq $null
True

$matches 中不应该有匹配组吗?

【问题讨论】:

  • 显示一个包含实际数据的示例 - 您的正则表达式和匹配的文本。

标签: regex powershell


【解决方案1】:

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

如果文件包含一行(第一个运算符有效),您的示例应该可以按预期工作。 如果文件包含 2+ 行,则使用第二个运算符并且不设置 $matches

应用于集合的其他布尔运算符也是如此。 即collection -op ... 返回item -op ... 为真的项目。

例子:

1..10 -gt 5 # 6 7 8 9 10
'apple', 'banana', 'orange' -match 'e' # apple, orange 

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

$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'
}

-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!'
}

【讨论】:

  • 是的,就是这样。我的 get-content 返回一个数组,最后一行不匹配,导致 $matches 清空。
  • 非常彻底的答案,@Roman!对于另一个观点(以及爱丽丝梦游仙境的转折!)感兴趣的读者也可以看看我在 Simple-Talk.com 上发表的文章Harnessing PowerShell's String Comparison and List-Filtering Features。文章随附的挂图说明了标量和数组上下文中的 -match 运算符(和变体)以及许多其他运算符。
  • 快速注意,尝试使用foreach.. 循环遍历数组的成员(可能创建一个条件来检查$obj.gettype()),然后您可以根据需要使用-match。 . 值得注意的是这种寻找特定匹配的策略stackoverflow.com/a/3520237/843000
  • Get-Clipboard = 收藏; Get-Clipboard -Raw = 字符串。学会了艰难的路......
【解决方案2】:

我遇到了同样的问题,确切的行在 Powershell 命令提示符下工作,但不是来自 Powershell ISE 或普通命令提示符。如果您不想使用 foreach 逐一循环浏览文件的所有行,您可以简单地将其转换为这样的字符串,然后它应该可以工作:

if([string](Get-Content -path $filePath) -match $pattern)
{
   $matches[1]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多