PowerShell: How to Check if String Contains Special Characters


Often in PowerShell you may want to check if a string contains any special characters.

You can use the following syntax to do so:

$my_string -match '[^a-zA-Z0-9 ]'

This particular example checks if the string variable named $my_string contains any special characters and returns True if it does or False otherwise.

This syntax uses the -match operator to check if there are any characters that do not match ( ^ ) any of the following characters:

  • a-z: Any lowercase letters
  • A-Z: Any uppercase letters
  • 0-9: Any numbers

Note: We also included a space at the end of the brackets so that a space is not considered a special character. Feel free to leave this out if you’d like.

The following example shows how to use this syntax in practice.

Example: How to Check if String Contains Special Characters in PowerShell

Suppose that we create a string variable named $my_string with the following text:

  • I am the proud owner of 3 dogs

We can use the following syntax to check if this string contains any special characters:

$my_string = 'I am the proud owner of 3 dogs'
$my_string -match '[^a-zA-Z0-9 ]' 

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

This returns False, which indicates that the string variable named $my_string does not contain any special characters.

We can verify that this is correct by manually looking at the string and seeing that it only contains numbers, letters and spaces.

Suppose instead that we create a string variable named $my_string with the following text:

  • I am the proud owner of $3

We can use the following syntax to check if this string contains any special characters:

$my_string = 'I am the proud owner of $3'
$my_string -match '[^a-zA-Z0-9 ]' 

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

PowerShell check if string contains special characters

This returns True, which indicates that the string variable named $my_string contains at least one special character.

In this particular example the dollar sign ( $ ) in the string is considered a special character, which is why the -match operator returns True.

Note: You can find the complete documentation for the -match operator in PowerShell here.

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 Special Characters in String
PowerShell: How to Replace Text in String
PowerShell: How to Concatenate Strings

Leave a Reply