PowerShell 无法在反向引用匹配项上使用方法

3
我努力尝试动态转换大小写,但似乎PowerShell方法不适用于后向引用匹配,例如下面的示例:
$a="string"
[regex]::replace( "$a",'(.)(.)',"$('$1'.toupper())$('$2'.tolower())" )
> string
$a -replace '(.)(.)',"$('${1}'.toupper())$('${2}'.tolower())"
> string

expected result
> StRiNg

不知道是否可能

1个回答

4

您需要使用脚本块来调用String类的方法。这样您可以有效地实现您想要的功能。在Windows PowerShell中,您无法使用-replace操作符进行脚本块替换。不过,在PowerShell Core(v6+)中是可以做到的:

# Windows PowerShell
$a="string"
[regex]::Replace($a,'(.)(.)',{$args[0].Groups[1].Value.ToUpper()+$args[0].Groups[2].Value.ToLower()})

# PowerShell Core
$a="string"
$a -replace '(.)(.)',{$_.Groups[1].Value.ToUpper()+$_.Groups[2].Value.ToLower()}

请注意,脚本块替换会识别当前的MatchInfo对象($_)。 在使用Replace()方法时,除非您指定param()块,否则脚本块将作为自动变量$args传递给MatchInfo对象作为参数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接