Regular expressions (regex) are used to define filters. It contains the characters to define the pattern of the text to be matched. In PowerShell, we can use PowerShell split operator with a regex pattern to split a string into multiple substrings.
In this example, we will discuss how to use regex with PowerShell split operator and PowerShell split regex examples.
PowerShell Split Regex Pattern to split string
To split a string into multiple substrings based on a regex pattern, use the split operator.
Let’s consider an example to understand the PowerShell string split regex with date example.
$sysdate = "01-08-2022" # use Regex patter with split operator $sysdate -split '(.*)-\d+-([^-]+)'
In the above PowerShell script, the $sysdate variable contains the date. We want to split the string to get the first and last element from the string example, day and year.
We have used the regex pattern (.*)-\d+-([^-]+) that matches the text in the given string and split the string to get the first and last element.
The output of the above PowerShell script after using the split regex pattern is:
PS C:\> $sysdate -split '(.*)-\d+-([^-]+)'
01
2022
PowerShell Regex Split on Whitespace
Using the split operator with the regex pattern, you can easily split the string by whitespace into multiple substrings.
$my_text = "Hello! Welcome to ShellGeek" $my_text -split "\s{1,}"
In the above PowerShell script, the $my_text variable stores the string that contains one or more whitespace in it.
To Split the string on whitespace, we have used PowerShell split operator with regex pattern \s{1,}
The regex patterns match for one or more occurrences of whitespace in the given string and split it into multiple substrings.
The output of the above PowerShell split regex on whitespace character is:
PS C:\> $my_text = "Hello! Welcome to ShellGeek"
PS C:\> $my_text -split "\s{1,}"
Hello!
Welcome
to
ShellGeek
PS C:\>
Cool Tip: How to split string to get the last element in PowerShell!
Conclusion
I hope the above article on how to split strings using the regex patterns in PowerShell is helpful to you.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.