我正在使用正则表达式来匹配文件内容:
> (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)
Piy*_*oni 10
我有同样的问题,确切的行是从Powershell命令提示符,但不是从Powershell ISE或正常的命令提示符.如果你不想使用foreach逐个遍历文件的所有行,你可以简单地将它转换为这样的字符串,它应该工作:
if([string](Get-Content -path $filePath) -match $pattern)
{
$matches[1]
}
Run Code Online (Sandbox Code Playgroud)