PowerShell: How to Split String with Different Whitespaces


Often you may want to use PowerShell to split a string in which a different number of whitespace characters separate the values in the string.

If you attempt to use the split operator with the following syntax then each individual whitespace character will be used as a delimiter:

$my_string.split()

Instead, you must use split as a unary operator with the following syntax:

-split $my_string

This syntax will split the string stored in the variable named $my_string using one or more whitespaces as the delimiter.

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

Example: How to Split a String with Different Whitespaces in PowerShell

Suppose we define a string variable named $my_string in PowerShell that contains the names of various basketball teams.

$my_string = "Mavs Lakers   Nets  Rockets Kings"

Notice that not all of the team names are separated by the same number of whitespaces.

Suppose we attempt to use the following syntax to split the team names in this string:

$my_string.split()

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

Notice that individual whitespaces are used as the delimiter, so several whitespaces are shown in the output.

Instead, we can use the following syntax to split the values in the array using one or more whitespaces as the delimiter:

-split $my_string

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

PowerShell split string with different whitespaces

Notice that the output now only contains one team name per line.

By using -split as the first command, we were able to split the string using one or more spaces as the delimiter.

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

Related Tutorials

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

PowerShell: How to Split String Based on Regex Pattern
PowerShell: How to Split String Based on Tab Characters
PowerShell: How to Split a String Using Multiple Delimiters
PowerShell: How to Split String into Separate Variables

Leave a Reply