为什么在 powershell 中使用替换运算符时无法对匹配组执行操作?

Why actions can not be done on match groups when using replace operator in powershell?

为什么当我执行以下脚本时:

'abc abc abc' -replace '\w+', '[=10=] abc'.ToUpper()

我得到 abc ABC abc ABC abc ABC 而不是 ABC ABC ABC ABC ABC ABC?

此外,如果我执行

'abc abc abc' -replace '\w+', '[=11=] abc'.ToCharArray()

我得到$ 0 a b c $ 0 a b c $ 0 a b c

是否可以对匹配组进行一些操作?

作为 .ToUpper() 调用在 字符串传递给 -replace 之前执行

如果您想以编程方式访问每个替代品,请直接使用 [regex]::Replace()

[regex]::Replace('abc abc abc', '\w+', {"$($args[0].Value) abc".ToUpper()})

... 或者,如果您使用的是 PowerShell 6.1 或更新版本,-replace 还支持用于替代评估的脚本块:

'abc abc abc' -replace '\w+', {"$($_.Value) abc".ToUpper()}