3

i tried harder to convert the case on the fly but it seems that powershell methods does not run for backrefence matches example below:

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

expected result
> StRiNg

don't know if it's possible or not

1 Answers1

4

You need a script block to call the String class methods. You can effectively do what you want. For Windows PowerShell, you cannot do script block substitutions with the -replace operator. You can do that in PowerShell Core (v6+) though:

# 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()}

Note that the script block substitution recognizes current MatchInfo object ($_). Using the Replace() method, the script block is passed in the MatchInfo object as an argument in the automatic variable $args unless you specify a param() block.

AdminOfThings
  • 23,946
  • 4
  • 17
  • 27