user1604008
user1604008

Reputation: 1025

using matched patterns in powershell -replace

The following prints out 123$replace456, I'd like it to print 123yyy456. How do I do this in powershell?

  $path = '123xxx456'
  $search = "(\d*)xxx(\d*)"
  $replace = 'yyy'
  $path -replace $search, '$1$replace$2'

Upvotes: 1

Views: 44

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

Use a double-quoted string for the replacement pattern in order for $replace to expand correctly. Remember to escape the $ in front of backreferences (ie `$1):

$path -replace $search, "`$1$replace`$2"

Upvotes: 1

Related Questions