PowerShell: How to Replace Special Characters in String


You can use the following methods to replace special characters in a string in PowerShell:

Method 1: Remove everything except letters

$new_string = $my_string -replace ('[^a-zA-Z]', '')

Method 2: Remove everything except letters and numbers

$new_string = $my_string -replace ('[^a-zA-Z]\d', '')

Method 3: Remove specific special characters

$new_string = $my_string -replace ('[!$%#]', '')

The following examples show how to use each method in practice.

Example 1: Remove Everything Except Letters in String in PowerShell

Suppose that we would like to use PowerShell to remove everything from a string except for alphabetical letters.

We can use the following syntax to do so:

$my_string = '4P%enny$)~^Lane#-3!'
$new_string = $my_string -replace ('[^a-zA-Z]', '')
$new_string

The following screenshot shows how to use this syntax in practice:

Notice that all characters except for alphabetical letters have been removed from the string.

The original string was: 4P%enny$)~^Lane#-3!

The new string is: PennyLane

Example 2: Remove Everything Except Letters and Numbers in String in PowerShell

Suppose that we would like to use PowerShell to remove everything from a string except for alphabetical letters and numbers.

We can use the following syntax to do so:

$my_string = '4P%enny$)~^Lane#-3'
$new_string = $my_string -replace ('[^a-zA-Z\d]', '')
$new_string

The following screenshot shows how to use this syntax in practice:

Notice that all characters except for alphabetical letters and numbers have been removed from the string.

The original string was: 4P%enny$)~^Lane#-3!

The new string is: 4PennyLane3

Example 3: Remove Specific Special Characters in String in PowerShell

Suppose that we would like to use PowerShell to remove the following special characters from a string:

  • !
  • $
  • %
  • #

We can use the following syntax to do so:

$my_string = '4P%enny$)~^Lane#-3'
$new_string = $my_string -replace ('[!$%#]', '')
$new_string

The following screenshot shows how to use this syntax in practice:

Notice that only the four special characters that we specified have been removed from the string.

The original string was: 4P%enny$)~^Lane#-3!

The new string is: 4Penny)~^Lane-3

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text in String
PowerShell: How to Concatenate Strings

Leave a Reply