问题描述
我更努力地即时转换案例,但似乎powershell方法不会运行反向引用匹配以下示例:
$a="string"
[regex]::replace( "$a",'(.)(.)',"$('$1'.toupper())$('$2'.tolower())" )
> string
$a -replace '(.)(.)',"$('${1}'.toupper())$('${2}'.tolower())"
> string
expected result
> StRiNg
不知道有没有可能
解决方法
您需要一个脚本块来调用 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
块,否则脚本块将作为自动变量 $args
中的参数传入 param()
对象。