powershell 不能在反向引用匹配上使用方法

问题描述

我更努力地即时转换案例,但似乎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() 对象。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...