Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell -replace when replacement string contains $+

I am doing a string replacement in PowerShell. I have no control over the strings that are being replaced, but I can reproduce the issue I'm having this way:

> 'word' -replace 'word','@#$+'
@#word

When the actual output I need is

> 'word' -replace 'word','@#$+'
@#$+

The string $+ is being expanded to the word being replaced, and there's no way that I can find to stop this from happening. I've tried escaping the $ with \ (as if it was a regex), with backtick ` (as is the normal PowerShell way). For example:

> 'word' -replace 'word',('@#$+' -replace '\$','`$')
@#`word

How can I replace with a literal $+ in PowerShell? For what it's worth I'm running PowerShell Core 6, but this is reproducible on PowerShell 5 as well.

like image 942
Mark Henderson Avatar asked Aug 24 '26 07:08

Mark Henderson


2 Answers

Instead of using the -replace operator, you can use the .Replace() method like so:

PS> 'word'.Replace('word','@#$+')
@#$+

The .Replace() method comes from the .NET String class whereas the -Replace operator is implemented using System.Text.RegularExpressions.Regex.Replace().

More info here: https://vexx32.github.io/2019/03/20/PowerShell-Replace-Operator/

like image 132
Brandon Olin Avatar answered Aug 26 '26 18:08

Brandon Olin


It's confusing how these codes aren't documented under "about comparison operators". Except I have a closed bug report about them underneath if you look, 'wow, where are all these -replace 2nd argument codes documented?'. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7 That's become my reference. "$+" means "Substitutes the last submatch captured". Doubling up the dollar signs works, 'substitutes a single "$" literal':

'word' -replace 'word','@#$$+'

@#$+

Or use the scriptblock version of the second argument in PS 6 and above (may be slower):

'word' -replace 'word',{'@#$+'}
like image 30
js2010 Avatar answered Aug 26 '26 17:08

js2010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!