PowerShell: How to Split String on First Occurrence of Pattern


Often you may want to split a string in PowerShell based only on the first occurrence of a pattern so that you’re left with only two elements after the split.

You can use the following syntax to do so:

$first, $second = $my_string -split ",", 2

This particular example splits the string stored in the variable named $my_string using a comma as the separator and specifies that only 2 strings should be returned.

If we didn’t include the 2 at the end then the -split operator would simply keep splitting the string each time it encountered a comma.

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

Example: Split String Only on First Occurrence of Pattern in PowerShell

Suppose we create a string variable named $my_string in PowerShell that contains information about various basketball teams:

  • “Team Names,Mavs,Nets,Rockets,Spurs”

Suppose that we use the following syntax with the -split operator to split this string into individual elements based on wherever commas occur:

$my_string = "Team Names,Mavs,Nets,Rockets,Spurs"

$my_string -split ","

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

Notice that the -split operator splits the string on each occurrence of a comma and returns a total of five elements.

We can instead use the following syntax to split the string only on the first occurrence of a comma:

$my_string = "Team Names,Mavs,Nets,Rockets,Spurs"

$first, $second = $my_string -split ",", 2

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

PowerShell split string only on first occurrence

Notice that the variable $first now contains the text “Team Names” while the variable $second contains all remaining text in the string.

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 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