Table of Contents
Using Regex.Replace()
Method
Use the Regex.Replace()
method to remove special characters from the specified string in PowerShell.
1 2 3 4 5 6 7 8 9 |
$str = "How #$%are ^&*you?@!" $cleanedStr = [System.Text.RegularExpressions.Regex]::Replace($str, '[^\w\s]', '') Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: How are you |
First, we declared a variable named $str
and set its value to a string containing some special characters. Then, we used the Replace()
method of the Regex
class from the System.Text.RegularExpressions
namespace to replace the special characters with an empty string.
The Replace()
method took three arguments: the string ($str
), the regular expression ('[^\w\s]'
), and an empty string (''
). The regular expression pattern matched any character that was not a word character (represented by \w
) or whitespace character (denoted by \s
). Here, ^
meant negation. Note that the replacement string was empty (''
), removing matched special characters from the input string.
Next, we used the Write-Host
cmdlet to display the original and cleaned string on the PowerShell console; the @"..."@
notation was used to write a multiline statement.
The word characters are
[a-zA-Z0-9_]
.
Remember, if the System.Text.RegularExpressions
namespace is not available in your system already, then use the Add-Type
cmdlet as follows:
1 2 3 4 5 |
Add-Type -TypeDefinition @" using System.Text.RegularExpressions; "@ |
The Add-Type
cmdlet dynamically adds an assembly or a .NET type to the PowerShell session. This cmdlet is needed if the required namespace is not available already.
Similarly, we use the Regex.Replace()
method inside the ForEach
loop to remove special characters from an array of strings in PowerShell.
1 2 3 4 5 6 7 8 9 10 11 12 |
$strArray = @("How #$%are ^&*you?@!", "Hello $&World") $cleanedStr = foreach ($string in $strArray) { [System.Text.RegularExpressions.Regex]::Replace($string, '[^\w\s]', '') } Write-Host @" Original Array of Strings: $strArray Cleaned Array of Strings: $cleanedStr "@ |
1 2 3 4 |
Original Array of Strings: How #$%are ^&*you?@! Hello $&World Cleaned Array of Strings: How are you Hello World |
In the above code fence, we created an array of strings using an array operator (@()
) and assigned this array to the $strArray
variable. Next, we used the ForEach
loop to iterate over the $strArray
. After that, we used the Regex.Replace()
method in each iteration to remove special characters from the current string ($string
). We have learned about the Regex.Replace()
method with previous code examples; you can refer to that.
We assigned the cleaned strings to the $cleanedStr
variable. Finally, we used the Write-Host
cmdlet to print the original and updated array of strings on the console.
Using String.Replace()
Method
Use the String.Replace()
method to remove special characters from the specified string in PowerShell. This approach is useful when removing a particular special character(s).
1 2 3 4 5 6 7 8 9 10 11 |
$str = "How #$%are ^&*you?@!" $specialChars = @('#','$','%','^','&','*','@','!') echo "Original String: $str" ForEach ($character in $specialChars) { $str = $str.Replace($character, '') } echo "Cleaned String: $str" |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: How are you? |
Again, we have $str
containing special characters. Then, we used an array operator (@()
) to create an array where each item was a special character we did not want in the output string. We stored this array in the $specialChars
variable. Next, we used the echo
command to display the $str
on the PowerShell console.
After that, we used the ForEach
loop (a.k.a. ForEach
statement) to iterate over the $specialChars
. We invoked the Replace()
method of the String
class in each iteration. It took two arguments, the current character and an empty string; here, we wanted to replace the matched current character with an empty string.
Notice that we updated the $str
in every iteration. Finally, we used another echo
to print the updated $str
.
Similarly, we use the String.Replace()
method inside the nested ForEach
loop to remove special characters from an array of strings in PowerShell.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$strArray = @("How #$%are ^&*you?@!", "Hello $&World") $specialChars = @('#','$','%','^','&','*','@','!') echo "Original Array of Strings: $strArray" ForEach ($index in 0..($strArray.Length - 1)) { ForEach ($character in $specialChars) { $strArray[$index] = $strArray[$index].Replace($character, '') } } echo "Cleaned Array of Strings: $strArray" |
1 2 3 4 |
Original Array of Strings: How #$%are ^&*you?@! Hello $&World Cleaned Array of Strings: How are you? Hello World |
This example is comparable to the last one, which had an array of strings ($strArray
), an array of special characters ($specialChars
), and used the echo
command to display the $strArray
on PowerShell console.
Then, we used the nested ForEach
loop. The outer loop was responsible for iterating over the $strArray
; it used the $index
variable to access each element in the $strArray
. The inner loop was accountable for looping over the $specialChars
array.
Inside the inner ForEach
loop, we used the String.Replace()
method to effectively replace the special character with an empty string to draw them out from the string. Lastly, we used another echo
to display the updated array of strings.
Using -replace
Operator
The -replace
operator can be used with different variations of a regular expression to remove special characters from the given string or array of strings. Let’s learn them using the -replace
operator.
Use the -replace
operator with regex, specified via ranges, to remove special characters from the specified string in PowerShell.
1 2 3 4 5 6 7 8 |
$str = "How #$%are ^&*you?@!" $cleanedStr = $str -replace '[^a-zA-Z0-9\s]', '' Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: How are you |
Use the -replace
operator with regex, written using ASCII characters, to remove special characters from the specified string in PowerShell.
1 2 3 4 5 6 7 8 |
$str = "How #$%are ^&*you?@!" $cleanedStr = $str -replace '[^\x30-\x39\x41-\x5A\x61-\x7A\x20]+', '' Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: How are you |
Use the -replace
operator with regex, written using Unicode characters, to remove special characters from the specified string in PowerShell.
1 2 3 4 5 6 7 8 |
$str = "How #$%are ^&*you?@!" $cleanedStr = $str -replace '[^\u0030-\u0039\u0041-\u005A\u0061-\u007A\u0020]+', '' Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: How are you |
Use the -replace
operator with regex specified using meta character (\W
) to remove special characters from the specified string in PowerShell.
1 2 3 4 5 6 7 8 |
$str = "How #$%are ^&*you?@!" $cleanedStr = $str -replace '[\W]', '' Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: Howareyou |
Use the -replace
operator with the regular expression written using Unicode categories to remove special characters from the specified string in PowerShell.
1 2 3 4 5 6 7 8 |
$str = "How #$%are ^&*you?@!" $cleanedStr = $str -replace '[^\p{L}\p{Nd}]', '' Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: Howareyou |
Alternatively, you can do as follows if you want to keep some special characters based on the project’s needs.
1 2 3 4 5 6 7 8 |
$str = "How #$%are ^&*you?@!" $cleanedStr = $str -replace '[^\p{L}\p{Nd}/?/!/\s]', '' Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: How are you?! |
The above examples in this section resembled one another and had a $str
containing special characters. They all used the -replace
operator with a regex to remove special characters by replacing them with an empty string. We assigned the cleaned string to the $cleanedStr
variable.
Moreover, the above examples used the Write-Host
cmdlet to print the primary and updated string on the PowerShell console. They only differed in specifying the regular expression. Let’s learn them below.
[^a-zA-Z0-9\s]
– This regex pattern matched all characters excluding the alphabets (a-z
andA-Z
), numbers (0-9
), and a space character (\s
).[^\x30-\x39\x41-\x5A\x61-\x7A\x20]+
– This regex pattern was written using ASCII characters; it matched all characters excluding the numbers ranging from0
to9
(\x30-\x39
), upper case alphabets (\x41-\x5A
), lower case alphabets (\x61-\x7A
), and a space character (\x20
). Here,+
indicates the preceding group or character class should have at least one or multiple occurrences.[^\u0030-\u0039\u0041-\u005A\u0061-\u007A\u0020]+
– This regex was similar to the last one but specified using Unicode characters. It matched all characters excluding the numbers 0-9 (\u0030-\u0039
), upper case and lower case letters (\u0041-\u005A
and\u0061-\u007A
), and a space character (\u0020
).[\W]
– Matched any non-word character. Remember the word characters are[a-zA-Z0-9_]
. So, you must not use this regex if you don’t need underscore (_
) in your output string.[^\p{L}\p{Nd}]
– It matched all characters that were not the letters or digits. Here,\p{L}
matched any Unicode letter characters, including the letters from different languages or scripts. While the\p{Nd}
matched any Unicode decimal digit character.[^\p{L}\p{Nd}/?/!/\s]
– This regex is similar to the above but used when we want to keep certain special characters. In this case, it kept the?
,!
, and a space character (\s
) in the output string.
In the above regular expressions, the ^
means the negation, while []
were used to define the character class or group.
The ASCII and Unicode characters in a regular expression are prefixed by
\x
and\u
escape sequences. On the other hand, the\p
escape sequence represents the Unicode character category.
Use the -replace
operator to remove special characters from an array of strings in PowerShell.
1 2 3 4 5 6 7 8 9 10 11 |
$strArray = @("How #$%are ^&*you?@!", "Hello $&World") $specialChars = '[^\w\s]+' $cleanedStr = $strArray -replace $specialChars, '' Write-Host @" Original Array of Strings: $strArray Cleaned Array of Strings: $cleanedStr "@ |
1 2 3 4 |
Original Array of Strings: How #$%are ^&*you?@! Hello $&World Cleaned Array of Strings: How are you Hello World |
Using Char.IsLetterOrDigit
Method
Use the Char.IsLetterOrDigit()
method to remove special characters from the given string in PowerShell.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$str = "How #$%are ^&*you?@!" $cleanedStr = "" ForEach ($char in $str.ToCharArray()) { if ([Char]::IsLetterOrDigit($char)) { $cleanedStr += $char } } Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: Howareyou |
We created two string variables; one had a string value with special characters ($str
), and the other was initialized with an empty string ($cleanedStr
). Then, we used the ForEach
loop to iterate over the character array, which we created using the ToCharArray()
method as $str.ToCharArray()
.
Inside the loop, we used the if
statement with the IsLetterOrDigit()
method to check if the current character represented by $char
was a letter or digit. If it was, we appended the $cleanedStr
with $char
using the +=
operator to omit the special characters effectively. Finally, we used the Write-Host
cmdlet to print the original and updated string on the console.
To keep space characters in your output string, use the Char.IsWhiteSpace()
method as demonstrated below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$str = "How #$%are ^&*you?@!" $cleanedStr = "" ForEach ($char in $str.ToCharArray()) { if ([Char]::IsLetterOrDigit($char) -or [Char]::IsWhiteSpace($char)) { $cleanedStr += $char } } Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: How are you |
See the following code example to remove special characters from an array of strings using PowerShell.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$strArray = @("How #$%are ^&*you?@!", "Hello $&World") $cleanedStrArray = @() foreach ($string in $strArray) { $cleanedStr = "" foreach ($char in $string.ToCharArray()) { if ([Char]::IsLetterOrDigit($char) -or [Char]::IsWhiteSpace($char)) { $cleanedStr += $char } } $cleanedStrArray += $cleanedStr } Write-Host @" Original Array of Strings: $strArray Cleaned Array of Strings: $cleanedStrArray "@ |
1 2 3 4 |
Original Array of Strings: How #$%are ^&*you?@! Hello $&World Cleaned Array of Strings: How are you Hello World |
This example is similar to the last ones for removing special characters from an array of strings. The outer loop iterated over the array of strings ($strArray
), while the inner loop iterated over the character array for the current string, which was converted as $string.ToCharArray()
.
We used the if
statement inside the inner loop with the IsLetterOrDigit()
and IsWhiteSpace()
methods. These methods took the current character ($char
) and determined if it was the letter, digit, or whitespace. If it was, then concatenated with the $cleanedStr
variable using the +=
operator.
Once the inner loop was finished, the $cleanedStr
was append to the $cleanedStrArray
using the +=
operator in the outer loop. Finally, we used Write-Host
to display the original and updated array of strings on the PowerShell console.
Using String.Join()
Method
Use the String.Join()
method to remove special characters from the input string in PowerShell.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$str = "How #$%are ^&*you?@!" $cleanedStr = [String]::Join('', ($str.ToCharArray() | Where-Object { $_ -match '\w|\s' })) Write-Host @" Original String: $str Cleaned String: $cleanedStr "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Cleaned String: How are you |
We used the String.Join()
method, which took two arguments. The first was the empty string. While for the second argument, we converted the string to the character array using the ToCharArray()
and piped it to the Where-Object
cmdlet.
This cmdlet iterated over the character array, matched the current character ($_
) with the \w|\s
pattern using the -match
operator, and joined them using an empty string (the first argument). In the \w|\s
pattern, the \w
matched the word character, while \s
matched a space character. Finally, we used the Write-Host
cmdlet to display the results on the console.
Use the String.Join()
method to remove special characters from an array of strings in PowerShell.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$strArray = @("How #$%are ^&*you?@!", "Hello $&World") $cleanedStrArray = @() ForEach ($string in $strArray) { $cleanedStrArray += [String]::Join('', ($string.ToCharArray() | Where-Object { $_ -match '\w|\s' })) } Write-Host @" Original String: $strArray Cleaned String: $cleanedStrArray "@ |
1 2 3 4 |
Original String: How #$%are ^&*you?@! Hello $&World Cleaned String: How are you Hello World |
This code snippet is similar to the last one, but we used ForEach
to loop over the $strArray
and stored the cleaned strings in the $cleanedStr
array.
That’s all about PowerShell remove special characters from String.