PowerShell: How to Split String Based on Regex Pattern


You can use the -split operator in PowerShell to split a string based on a particular Regex (regular expression) pattern.

You can use the following basic syntax to do so:

"Mavs3Spurs4Nets7Celtics6Raptors" -split "\d"

This particular example will split the string based on where any numeric value ( \d ) occurs.

Note that you can use any Regex pattern you would like in the quotes following the -split operator to split the string based on a specific pattern.

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

Example: How to Split a String Based on Regex Pattern in PowerShell

Suppose we have the following string in PowerShell:

  • Mavs3Spurs4Nets7Celtics6Raptors

This string contains the names of various basketball teams separated by various numbers.

We can use the following syntax to split this string based on where any number occurs:

"Mavs3Spurs4Nets7Celtics6Raptors" -split "\d"

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

PowerShell split string based on regex

We can see that the string has been split based on wherever a number occurs.

Note that we used the Regex pattern \d to match numbers between 0 and 9.

Note that we can also specify multiple Regex patterns to split on.

For example, suppose we have the following string in PowerShell:

  • Mavs, Spurs Nets, Celtics Raptors

We can use the following syntax to split this string based on where commas or spaces occur:

"Mavs, Spurs Nets, Celtics Raptors" -split "[\s,]+"

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

PowerShell split regex multiple patterns

Notice that the string has been split based on wherever spaces or commas occur.

Note that we used the syntax \s to match whitespace characters in the string.

We also used brackets to specify that each character within the brackets should be used as a potential delimiter.

Feel free to use any Regex pattern that you’d like following the -split operator to split your own string based on a specific pattern.

Related Tutorials

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

PowerShell: How to Split String into Separate Variables
PowerShell: How to Split File by Number of Lines
PowerShell: How to Split a String Using Multiple Delimiters

Leave a Reply