Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell variable in replacement string with named groups

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}".

like image 352
user957479 Avatar asked May 30 '15 07:05

user957479


People also ask

How do I replace a string with another string in PowerShell?

You can call the PowerShell replace method on any string to replace any literal string with another. If the string-to-be-replaced isn't found, the replace() method returns nothing. You don't need to assign a string to a variable to replace text in a string.

How do I replace multiple characters in a string in PowerShell?

You can replace multiple characters in a string using PowerShell replace() method or PowerShell replace operator. If you are using the PowerShell replace() method, you can chain replace() method as many times to replace the multiple characters in the PowerShell string.

How do I replace a character in a string in PowerShell?

In PowerShell we can use the Replace() method on any string or variable that is a string. The method needs two arguments, the text or character that you want to find and the with what you want to replace it with.

How do you replace a variable in PowerShell?

Use the PowerShell String replace() method or replace operator to replace the variable in a file. Use the Get-Content to read the content of the file and pipe it to replace() or replace operator. The replace() method returns a string where variables in a file are replaced by another variable.


1 Answers

@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.

  • msdn about replace operator
  • msdn about escape characters

or via Get-Help about_escape & Get-Help about_comparison_operators

like image 58
Vincent De Smet Avatar answered Oct 25 '22 06:10

Vincent De Smet