6

The following Powershell replace operation with named groups s1 and s2 in regex (just for illustration, not a correct syntax) works fine :

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

My question is : how to replace with a variable $x instead of the literal xxx, that is, something like :

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

That doesn't work as Powershell doesn't replace variable in single quoted string but the named group resolution doesn't work anymore if replacement string is put in double quotes like this "${s2}$x${s1}".

2
  • 1
    "`${s2}$x`${s1}" Commented May 30, 2015 at 8:51
  • Thanks, works perfectly ! It really makes sense when you have the answer ;-) Commented May 31, 2015 at 12:09

1 Answer 1

4

@PetSerAl comment is correct, here is code to test it:

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

Output: AAA,BBB

Explanation:

Powershell will evaluate the double quoted string, escaping the $ sign with a back tick will ensure these are not evaluated and a valid string is provided for the -Replace operator.

or via Get-Help about_escape & Get-Help about_comparison_operators

Sign up to request clarification or add additional context in comments.

1 Comment

You are the reason i still have hair on my head man. Thank you for this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.