Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell cannot use methods on backreference matches

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

like image 667
Kardof Zilaf Avatar asked Aug 23 '26 22:08

Kardof Zilaf


1 Answers

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.

like image 152
AdminOfThings Avatar answered Aug 25 '26 15:08

AdminOfThings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!