PowerShell – Case-insensitive String Replacement

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.

Thrid 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
c:\NewLocation\sometempfile.csv

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:

RegExOptions

Advertisements

6 thoughts on “PowerShell – Case-insensitive String Replacement

    1. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s