Powershell:匹配运算符返回 true 但 $matches 为 null [英] Powershell: match operator returns true but $matches is null

查看:18
本文介绍了Powershell:匹配运算符返回 true 但 $matches 为 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working with a regex to match file contents:

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

这返回真,一个匹配,但是我的 $matches 变量仍然为空.

this returns true, a match, however my $matches variable remains null.

> $matches -eq $null
True

$matches 中不应该包含匹配组吗?

Shouldn't $matches have the match groups in it?

推荐答案

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

Strictly speaking string -match ... and collection -match ... are two different operators. The first gets a Boolean value and fills $matches. The second gets each collection item that matches a pattern and apparently does not fill $matches.

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

Your example should work as you expect if the file contains a single line (the first operator works). If a file contains 2+ lines then the second operator is used and $matches is not set.

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

The same is true for other Boolean operators applied to a collection. That is collection -op ... returns items where item -op ... is true.

示例:

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

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

Boolean operators applied to collections are handy if used properly. But they may be confusing as well and lead to easy to make mistakes:

$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 的另一个例子可能看起来很混乱:

Another example with -match and -notmatch may look confusing:

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

这篇关于Powershell:匹配运算符返回 true 但 $matches 为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆