【问题标题】:powershell cannot use methods on backreference matchespowershell 不能对反向引用匹配使用方法
【发布时间】:2021-01-10 13:25:58
【问题描述】:
我更努力地即时转换大小写,但似乎 powershell 方法不适用于下面的反向引用匹配示例:
$a="string"
[regex]::replace( "$a",'(.)(.)',"$('$1'.toupper())$('$2'.tolower())" )
> string
$a -replace '(.)(.)',"$('${1}'.toupper())$('${2}'.tolower())"
> string
expected result
> StRiNg
不知道有没有可能
【问题讨论】:
标签:
powershell
backreference
【解决方案1】:
您需要一个脚本块来调用 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 对象。