can we mention the variable in - replace function example:
$value="V2"
$prop="Groovy=V3"
$prop -replace "(?<conf>Groovy)=(?<version>[vV]\d)" , "${conf}=${value}"
can we mention the variable in - replace function example:
$value="V2"
$prop="Groovy=V3"
$prop -replace "(?<conf>Groovy)=(?<version>[vV]\d)" , "${conf}=${value}"
${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}"
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