PowerShell: How to Split a String Using Multiple Delimiters


You can use the following basic syntax to split a string based on multiple potential delimiters:

$my_string.split(",;|")

This particular example will split the string variable named $my_string based on where any of the following delimiters occur:

  • ,
  • ;
  • |

Note that the split method will split a string using every individual character within the parenthesis.

If you would instead like to split on a particular string then you can use the -split operator instead:

$my_string -split(",;|")

This particular example will only split the string variable named $my_string where the characters ,;| all occur together.

The following example shows how to split a string based on multiple delimiters in practice.

Example: How to Split a String Using Multiple Delimiters in PowerShell

Suppose we define a string variable named $teams in PowerShell that contains the names of various basketball teams separated by several different delimiters.

We can use the following syntax to split the string variable based on where any of the following delimiters occur:

  • ,
  • ;
  • |
$teams = "Mavs,Nets,Hawks;Kings|Lakers,Cavs"
$teams.split(",;|")

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

PowerShell split string based on multiple delimiters

Notice that the string has been split based on where any of the three delimiters occured.

Note: If this syntax does not work in PowerShell 7 then you may need to use the following syntax instead:

$teams.split(",;|".ToCharArray())

Related Tutorials

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

PowerShell: How to Replace Text in String
PowerShell: How to Get String Length of Variable
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Check if String Exists in List of Strings

Leave a Reply