首页 > 解决方案 > powershell 不能对反向引用匹配使用方法

问题描述

我更努力地即时转换大小写,但似乎 powershell 方法不适用于下面的反向引用匹配示例:

$a="string"
[regex]::replace( "$a",'(.)(.)',"$('$1'.toupper())$('$2'.tolower())" )
> string
$a -replace '(.)(.)',"$('${1}'.toupper())$('${2}'.tolower())"
> string

expected result
> StRiNg

不知道有没有可能

标签: powershellbackreference

解决方案


您需要一个脚本块来调用 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()脚本块将MatchInfo作为自动变量中的参数传入对象。$argsparam()


推荐阅读