How to split string by string in Powershell
The -split
operator uses the string to split, instead of a chararray like Split()
:
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string -split $separator
5637144576, messag<>est
5637145326, 1
5637145328, 0
If you want to use the Split()
method with a string, you need the $seperator
to be a stringarray with one element, and also specify a stringsplitoptions value. You can see this by checking its definition:
$string.Split
OverloadDefinitions
-------------------
string[] Split(Params char[] separator)
string[] Split(char[] separator, int count)
string[] Split(char[] separator, System.StringSplitOptions options)
string[] Split(char[] separator, int count, System.StringSplitOptions options)
#This one
string[] Split(string[] separator, System.StringSplitOptions options)
string[] Split(string[] separator, int count, System.StringSplitOptions options)
$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = [string[]]@("<<>>")
$string.Split($separator, [System.StringSplitOptions]::RemoveEmptyEntries)
5637144576, messag<>est
5637145326, 1
5637145328, 0
EDIT: As @RomanKuzmin pointed out, -split
splits using regex-patterns by default. So be aware to escape special characters (ex. .
which in regex is "any character"). You could also force simplematch
to disable regex-matching like:
$separator = "<<>>"
$string -split $separator, 0, "simplematch"
Read more about -split
here.
Instaed of using Split
method, you can use split
operator. So your code will be like this:
$string -split '<<>>'