How .Replace() and -replace differ

by May 10, 2017

There are two ways of replacing text in a string: the Replace() method, and the –replace operator. They work fundamentally different.

Replace() is case-sensitive and replaces text with new text:

 
PS> 'Hello World.'.Replace('o', '0')
Hell0 W0rld

PS> 'Hello World.'.Replace('ell','oo')
Hooo World
 

The -replace operator is by default case-insensitive (use -creplace if you want case sensitivity). It accepts a regular expression, and that is what most people miss:

 
PS> 'Hello World.' -replace 'ell', 'oo'
Hooo World.

PS> 'Hello World.' -replace '.', '!'
!!!!!!!!!!!!
 

The second outcome surprises those that don’t know about regular expressions. If you want -replace to replace static text, make sure you escape your text:

 
PS> 'Hello World.' -replace [Regex]::Escape('.'), '!'
Hello World!
 

Twitter This Tip! ReTweet this Tip!