vineet
vineet

Reputation: 9

Replacing first character of each word without affecting the inside ones

I am trying to replace the first character of each key word in PowerShell but unable to find the correct pattern to get the required result. Somehow I am able to manage to get the replacement, but other values are affecting which are acting as a value i.e "Gii-test-api.ne" converting into "Gii$test$api$ne".

For example:

My string is (replacing - with $):

$values = -CertThumb 1234567 -serverCertThumb 75659600 -MaintenancePeriod 60 -apiProtocol https -Port 8973 -Uri Gii-test-api.ne

Expected output:

$CertThumb 1234567 $serverCertThumb 75659600 $MaintenancePeriod 60 $apiProtocol https $Port 8973 $Uri Gii-test-api.ne

Tried command:

$values.ToString() -replace ('^*\-','$')

Upvotes: 1

Views: 52

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

You may use the following regex replace where - chars are only matched if not preceded with a word char:

$values -replace '\B-','$'

Or, if you only want to replace - that is preceded with whitespace or at the start of the string:

$values -replace '(?<!\S)-','$'

Here, \B matches any location other than a word boundary (i.e. here, - only matches when not preceded with a letter, digit or _) and the (?<!\S) negative lookbehind matches a location in the string that is either start of string or is preceded with a whitespace.

Note that the replacement can be either '$' or '$$' (a literal $ in the replacement will be parsed here as a $ char, but in case you replace with a $+digit you will have to escape $ with another $).

See the regex demo.

enter image description here

Upvotes: 1

Related Questions