Powershell variable in a replacement string with named groups

The following Powershell operation replaces the named groups s1 and s2 with regex (just for illustration and not for the correct syntax) works fine:

$s -Replace "(?<s1>....)(?<s2>...)" '${s2}xxx${s1}'

My question is: how to replace the variable $ x instead of the literal xxx, i.e. something like:

$s -Replace "(?<s1>....)(?<s2>...) '${s2}$x${s1}'

This does not work, since Powershell does not replace the variable in a single quote string, but resolving group names does not work anymore if the replacement string is placed in double quotes like this "$ {s2} $ x $ {s1}".

+4
source share
1 answer

The @PetSerAl comment is correct, here is the code to check it:

$sep = ","
"AAA BBB" -Replace '(?<A>\w+)\s+(?<B>\w+)',"`${A}$sep`${B}"

Output : AAA,BBB

Explanation

Powershell , $ , , -Replace ​​ .

Get-Help about_escape Get-Help about_comparison_operators

+2

All Articles