为什么 Powershell 字符串匹配转义的正则表达式 return false 但仍然输出正确匹配?
Why does Powershell string match escaped regex return false but still output correct match?
下面的代码按原样工作。注释掉的行是不起作用的替代版本。
[string]$secretString = "Secret message: The agent
was a man called Bond
007 BOND, James MI5 London
....... end"
# [string]$agent = '007 BOND' # [regex]::Escape($agent)
[string]$result = $null
$secretString -match "(007 BOND[^\r\n]*)"
# $secretString -match "([regex]::Escape($agent)[^\r\n]*)"
$result = $Matches[0]
Write-Host "The full name of agent is: $result"
工作版本的输出是:
True
The full name of agent is: 007 BOND, James MI5 London
非工作版本的输出(取消注释 $agent
声明并将 $secretString -match
行从显式转换为转义)是:
False
The full name of agent is: 007 BOND, James MI5 London
怎么会这样?据我了解 Matching operators $Matches 自动变量应该被覆盖。
正好。如果我在 VS 中打开一个新终端,再次 运行 错误代码,我现在得到:
False
InvalidOperation:
15 | $result = $Matches[0]
| ~~~~~~~~~~~~~~~~~~~~~
| Cannot index into a null array.
消息传递和逻辑现在是一致的。这意味着我有两个问题。
- 我的正则表达式转义码有什么问题?
- 为什么
$Matches
自动变量没有被覆盖?在代码的第二个 运行 中,它应该被覆盖为 null,因为比较运算符匹配 returns 一个错误匹配。
如有任何建议,我们将不胜感激。
As for the second point,请查看此处有关匹配项的注释部分:
When $Matches is populated in a session, it retains the matched value until it's overwritten by another match. If -match is used again and no match is found, it doesn't reset $Matches to $null. The previously matched value is kept in $Matches until another match is found.
下面的代码按原样工作。注释掉的行是不起作用的替代版本。
[string]$secretString = "Secret message: The agent
was a man called Bond
007 BOND, James MI5 London
....... end"
# [string]$agent = '007 BOND' # [regex]::Escape($agent)
[string]$result = $null
$secretString -match "(007 BOND[^\r\n]*)"
# $secretString -match "([regex]::Escape($agent)[^\r\n]*)"
$result = $Matches[0]
Write-Host "The full name of agent is: $result"
工作版本的输出是:
True
The full name of agent is: 007 BOND, James MI5 London
非工作版本的输出(取消注释 $agent
声明并将 $secretString -match
行从显式转换为转义)是:
False
The full name of agent is: 007 BOND, James MI5 London
怎么会这样?据我了解 Matching operators $Matches 自动变量应该被覆盖。
正好。如果我在 VS 中打开一个新终端,再次 运行 错误代码,我现在得到:
False
InvalidOperation:
15 | $result = $Matches[0]
| ~~~~~~~~~~~~~~~~~~~~~
| Cannot index into a null array.
消息传递和逻辑现在是一致的。这意味着我有两个问题。
- 我的正则表达式转义码有什么问题?
- 为什么
$Matches
自动变量没有被覆盖?在代码的第二个 运行 中,它应该被覆盖为 null,因为比较运算符匹配 returns 一个错误匹配。
如有任何建议,我们将不胜感激。
As for the second point,请查看此处有关匹配项的注释部分:
When $Matches is populated in a session, it retains the matched value until it's overwritten by another match. If -match is used again and no match is found, it doesn't reset $Matches to $null. The previously matched value is kept in $Matches until another match is found.