TajniakOsz
TajniakOsz

Reputation: 91

-replace replaces RegEx group with its name

I have a replace statement like this:

$var1 = "http"
$var2 = "1.2.3.4"
$json = $json -replace '(url = ["''])(.*)(:\/\/)(.*)(["''])', "`$1$var1`$3$var2`$5"

It was supposed to leave below line as it is:

url = "http://1.2.3.4"

while it is being changed to

url = "http$31.2.3.4"

As far as I understand `$3 should be replaced with :// just like `$5 has been replaced with ".

Is there any rule that I'm constantly missing?

Edit:

I have checked on multiple computers and here's what I've found out:

  1. The same code works fine on other computers (tested on Windows Server 2016 and Windows 10),
  2. The same code works fine on Azure VM connected via Remote Desktop (Windows Server 2016),
  3. On my computer (Windows Server 2019) it fails as described,
  4. On the same VM as in point 2. using Remote Desktop from my computer it fails as well.

Now I really don't have any idea what's happening. Maybe something with locale?

Settings:

  • Location: US
  • Language: English (US)
  • Keyboard layout: PLP

Specific settings:

  • Number formats: -123,456,789.00
  • First day of a week: Monday
  • Time format: HH:mm:ss
  • Date format: yyyy-mm-dd

I know that this is seems not to be connected but I have no idea at all.

Edit2:

Seems like RegEx does not work as expected when first character after (even escaped) RegEx group is a number (even as variable). But still have no idea how to omit this.

Upvotes: 1

Views: 80

Answers (1)

user6811411
user6811411

Reputation:

  • To exactly match the leading quote I suggest to use a backreference with a nested group
  • To insert a variable into to the replacement string enclose the name in curly braces
  • the forward slash doesn't need to be escaped.
  • to insert a capture group (number $1) in the replacement which might interfere with the following text, enclose the number also in ${1} curly braces

## Q:\Test\2019\01\10\SO_54131783.ps1

$json = 'url = "http://localhost"'

$var1 = "http"
$var2  = "1.2.3.4"

$json = $json -replace '(url = (["''])).*?(://).*?(\2)',
                       "`${1}${var1}`${3}${var2}`${2}"
$json

url = "http://1.2.3.4"

Upvotes: 1

Related Questions