Lukasz Szczygielek
Lukasz Szczygielek

Reputation: 3129

String replace doesn't work when group identifier is near a variable in PowerShell

I have a PowerShell script like this:

$year = 2020
$string = 'Const conToYear As String = "2018"'
$newString = $string -replace '(Const conToYear As String = ")(\d{4})(")', "`$1$year`$3"
Write-Host $newString

It gives output $12020" but I need Const conToYear As String = "2020". I use in few places similar replace pattern, using groups and variables and they work.

What is funny, when I do:

$year = 2020
$string = 'Const conToYear As String = "2018"'
$newString = $string -replace '(Const conToYear As String = ")(\d{4})(")', "`$1`$1$year"
Write-Host $newString

Then I get Const conToYear As String = "$12020, so it looks like the second occurrence of $1 which is near variable is not interpreted as I expected.

How to solve this? I tried google it, but without success.

Upvotes: 1

Views: 47

Answers (2)

js2010
js2010

Reputation: 27516

Here's the powershell 6 and above version. Referring to the capture groups takes a little doing. But you don't have to mix variables and the replace operator special $ codes.

$year = 2020
$string = 'Const conToYear As String = "2018"'
$string -replace '(Const conToYear As String = ")(\d{4})(")',
  { $_.groups[1].value + $year + $_.groups[3].value }

Const conToYear As String = "2020"

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174700

Qualify your group numbers with {}:

$year = 2020
$string = 'Const conToYear As String = "2018"'
$newString = $string -replace '(Const conToYear As String = ")(\d{4})(")', "`${1}$year`${3}"
Write-Host $newString

Upvotes: 2

Related Questions