can we mention the variable in - replace function example:
$value="V2"
$prop="Groovy=V3"
$prop -replace "(?<conf>Groovy)=(?<version>[vV]\d)" , "${conf}=${value}"
Groovy)=(? can we mention the variable in - replace function
example: 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. Or simply the first capture group:
PowerShell String Replace function with variable value
278 Views
Asked by
try.aaam
At
$value="V2"
$prop="Groovy=V3"
$prop -replace "(?<conf>Groovy)=(?<version>[vV]\d)" , "${conf}=${value}"
There are 2 best solutions below
On
$value = 'V2'
'Groovy=V3' -replace '(?<conf>Groovy)=[vV]\d',
{ $_.groups['conf'].value + '=' + $value }
Groovy=V2
$value = 'V2'
'Groovy=V3' -replace '(Groovy)=[vV]\d', { $_.groups[1].value + '=' + $value }
Groovy=V2
${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-replaceoperator:Another option is to escape the
$with a backtick: