1

can we mention the variable in - replace function example:

$value="V2"
$prop="Groovy=V3"

$prop -replace "(?<conf>Groovy)=(?<version>[vV]\d)" , "${conf}=${value}"
try.aaam
  • 23
  • 1
  • 7
  • ``$prop -replace "(?Groovy)=(?[vV]\d)" , "`${conf}=${value}"`` or ``$prop -replace "(?Groovy)=(?[vV]\d)" , "`$1=${value}"`` – Theo Feb 21 '23 at 11:11

2 Answers2

3

${conf} is the correct syntax for referencing a capture in a regex substitution string, but it's also a valid PowerShell variable expression - so you need to replace the double-quotes around the substitute string with single-quotes to prevent PowerShell from attempting to expand the variables before the string is passed to the -replace operator:

$value="V2"
$prop="Groovy=V3"

$prop -replace "(?<conf>Groovy)=(?<version>[vV]\d)" , ('${conf}=' + ${value})

Another option is to escape the $ with a backtick:

$prop -replace "(?<conf>Groovy)=(?<version>[vV]\d)" ,"`${conf}=${value}"
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
1

Powershell 7 version with the scriptblock second argument. It may not be easier, but no special escaping of the "conf" named capture group is required.

$value = 'V2'
'Groovy=V3' -replace '(?<conf>Groovy)=[vV]\d', 
  { $_.groups['conf'].value + '=' + $value }

Groovy=V2

Or simply the first capture group:

$value = 'V2'
'Groovy=V3' -replace '(Groovy)=[vV]\d', { $_.groups[1].value + '=' + $value }

Groovy=V2
js2010
  • 23,033
  • 6
  • 64
  • 66