Edit:
After reviewing this question again, I've added a second example that I hope will highlight where my confusion became amplified, namely there was one capture group accessed by its index (1), and the value I expected from the $filecontent
was coincidentally also a 1.
This question indicates that a back tick can be used to address capture groups in a double quoted string when referencing other variables.
If you need to reference other variables in your replacement expression (as you may), you can use a double-quoted string and escape the capture dollars with a backtick
However, I'm seeing some interesting behavior that I can't explain.
$VersionReplacementRegex = "(\d+\.)\d+" #capture first digit + dot b/c I want to keep it
$BuildVersionValidationRegex = "\d+\.\d+\.\d+"
$VersionData = [regex]::matches("some-18.11.8",$BuildVersionValidationRegex)
$NewVersion = $VersionData[0] #matches 18.11.8
$filecontent = "stuff 1.0.0.0 other stuff" #Get-Content($file)
replacing text in $filecontent
using the capture group as specified in the linked question gives an incomplete result...
$filecontent -replace $VersionReplacementRegex, "`$1$NewVersion" | Write-Host
returns: 118.11.8
expected: 1.18.11.8
But adding a space between the $1
and $NewVersion
gives a different yet equally unhelpful result..
$filecontent -replace $VersionReplacementRegex, "`$1 $NewVersion" | Write-Host
returns: 1. 18.11.8
The captured dot appears here, but so does the undesirable space.
With this example, the results are somewhat similar, but it seems that the capture group is getting the wrong value all together.
$NewVersion = 18.11.8
$filecontent = "stuff 5.0.0.0 other stuff"
$filecontent -replace "(\d+\.)\d+", "`$1$NewVersion" | Write-Host
# returns: 118.11.8
# expected: 5.18.11.8
Adding the space in the replacement string returns: 5. 18.11.8
So, what am I missing, or is there a better way to do this?