下面的代码按原样工作。注释掉的行是替代版本,不起作用。
[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
:这会发生吗?据我了解 匹配运算符 $Matches 自动变量应该被覆盖。
碰巧的是。如果我在 VS 中打开一个新终端,再次运行错误代码,我现在会得到
False
InvalidOperation:
15 | $result = $Matches[0]
| ~~~~~~~~~~~~~~~~~~~~~
| Cannot index into a null array.
:现在逻辑是一致的。这意味着我有两个问题。
- 我的正则表达式转义代码有什么问题?
- 为什么
$Matches
自动变量没有被覆盖?在第二次运行代码时,应将其覆盖为 null,因为比较运算符匹配返回错误匹配。
任何建议将不胜感激。
The code below works as is. The commented out lines are the alternative version which does not work.
[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"
The output for working version is:
True
The full name of agent is: 007 BOND, James MI5 London
The output for non-working version (uncomment $agent
declaration & swap $secretString -match
line from explicit to escaped) is:
False
The full name of agent is: 007 BOND, James MI5 London
How can this happen? As I understand from Matching operators the $Matches automatic variable should be overwritten.
As it happens. If I open a new terminal in VS, to run the errant code again, I now get:
False
InvalidOperation:
15 | $result = $Matches[0]
| ~~~~~~~~~~~~~~~~~~~~~
| Cannot index into a null array.
The messaging & logic is now consistent. This means I have two problems.
- What is wrong with my regex escape code?
- Why is the
$Matches
automatic variable not being overwritten? On the second run of the code it should be overwritten to null because the comparison operator match returns a false match.
Any suggestions would be appreciated.
发布评论
评论(1)
至于第二点,查看这里有关匹配的注释部分:
As for the second point, check the note section here regarding matches: