-1

I am trying to use regex in powershell to replace text on a per line basis but it results in the entire line being replaced with the desired value but without the original leading text and with an unwanted dollar sign.

Example file with lines to replace:

server.ssl.keystore-password=ffdsfsa
server.ssl.key-password=ffdsaf

Example Regex:

KeyStorePassword='4Z9dwVQn6wSk5H3kWX2SsxGWhZ/jTUrwgDSyfYNCxN0='
'(server.ssl.key-password=).*',("`$1$KeyStorePassword")

But what ends up happening is it instead replaces the line as followed:

$4Z9dwVQn6wSk5H3kWX2SsxGWhZ/jTUrwgDSyfYNCxN0=

When the desired outcome is

server.ssl.key-password=4Z9dwVQn6wSk5H3kWX2SsxGWhZ/jTUrwgDSyfYNCxN0=
jwhit265
  • 21
  • 2
  • 1
    Are you married to using a Regex? You may want to consider using the builtin INI parsing capabilities outlined in this post: https://stackoverflow.com/questions/43690336/powershell-to-read-single-value-from-simple-ini-file This post covers writing: https://stackoverflow.com/questions/22802043/powershell-ini-editing – Frank Jan 11 '21 at 14:00
  • 1
    If you name your capture group, this problem goes away --> ```'(?server.ssl.key-password=).*',"`${field}$KeyStorePassword"``` – AdminOfThings Jan 11 '21 at 14:07

1 Answers1

0

The issue here is when $KeyStorePassword is interpolated, the beginning numbers (4 in this case) is appended to $1 making the substitution attempt to use capture group 14 ($14) instead of capture group 1. Naming your capture group prevents this or in this case surrounding your capture group name with {}.

# Using unnamed capture groups
'server.ssl.key-password=ffdsaf' -replace '(server\.ssl\.key-password=).*',"`${1}$KeyStorePassword"

In PowerShell, the named capture group syntax is (?<Name>match text). You can then substitute the capture group results with ${Name}.

# Using named capture groups
'server.ssl.key-password=ffdsaf' -replace '(?<field>server\.ssl\.key-password=).*',"`${field}$KeyStorePassword"

We can replicate the problem with a simpler example:

$ExtraNumber = 2
'98' -replace '(?<12>\d)(\d)',"`$1$ExtraNumber"
9

We name the first match to capture group 12. In the substitution, $ExtraNumber will be evaluated to 2 so the substituted group will be 12 ($12).

AdminOfThings
  • 23,946
  • 4
  • 17
  • 27
  • Thanks for the thorough explaining. So I'm guessing the only reason I'm running into problems is my replacement so happens to start with numbers. – jwhit265 Jan 11 '21 at 22:23
  • @jwhit265 yes that is the reason. The question was incorrectly closed and you were downvoted for no reason. Unfortunately, I cannot do anything about it. – AdminOfThings Jan 11 '21 at 22:41