The problem: Replace “a” with “b” case-insensitively
You have a simple string and you want to replace all “a” with “b” in a case-insensitive manner.
First attempt (fail):
PS C:\Windows\system32> [string] $someString = ‘aAaAaAaA’ $SomeString.Replace(‘a’, ‘b’) #Result bAbAbAbAbA |
What happened?
The [string].Replace() method is case-sensitive
Second attempt (looks like it works but not quite):
PS C:\Windows\system32> [string] $someString = ‘aAaAaAaA’ PS C:\Windows\system32> $someString -Replace ‘a’, ‘b’ #Result bbbbbbbbb |
What happened?
The PowerShell native -Replace seems works better and is case-insensitive by default.
Third attempt (fails):
PS C:\Windows\system32> #——————– #Repace “c:\temp” with “c:\NewLocation” #——————– $someString = ‘c:\temp\sometempfile.csv’ $replaceThis = ‘c:\temp’ $replaceWith = ‘c:\newlocation’ $someString -Replace $replaceThis, $replaceWith#Result c:\temp\sometempfile.csv |
What happened?
The PowerShell native -Replace works based on Regular Expressions and slashes have special meaning. So, our string did not get replaced as we intended. Notice that the result did not have “c:\temp” replaced with “c:\NewLocation”.
Fourth attempt (works!):
PS C:\Windows\system32> #——————– #Repace “c:\temp” with “c:\NewLocation” #——————– $someString = ‘c:\temp\sometempfile.csv’ $replaceThis = ‘c:\temp’ $replaceWith = ‘c:\newlocation’ [Regex]::Replace(` $someString, ` [regex]::Escape($replaceThis), ` $replaceWith, ` [System.Text.RegularExpressions.RegexOptions]::IgnoreCase); #Result |
There you have it!
We are simply escaping the string we are trying to replace from special Regular Expression interpretation and use the IgnoreCase option.
You could do this in a case-sensitive manner if you want. Here are the additional options available to you:
Thanks for trick.
You are welcome. It is one of those simple things you use often but don’t have it handy!
It can also be simplified a little bit like this:
$someString -ireplace [Regex]::Escape($replaceThis), $replaceWith
Nice and simple! Thank you.
Thanks both. Brecht’s version is tidier but still found the whole article useful.
What IDE are you using in that last screenshot with the Intellisense ?
I think I just inversed the colors of ISE screenshot. If not, it is probably from Visual Studio Code. Those are the only two editors I use.