After struggling with this for half an hour, I\'ve experienced this difference when splitting a string with spaces, depending on which syntax you use.
Simple string:
.Net object does not take regex but interprets it as a literal string.
$line = "1: 2: 3: 4: 5: "
$ln = $line.split("\s")
$ln
Output:
1: 2: 3: 4: 5:
Hence, in your example, the "+" is ignored as it it not found in $ln but ":\s" is used for splitting:
$ln = $line.split(":\s+")
$ln
Output:
1
2
3
4
5
which is same as
$ln = $line.split(":")
$ln
2.while powershell -split operator interprets "\s" as a valid regex i.e., space. Since, it can find both : and \s in the string, the combination of ":\s" is used for splitting. eg:
$line = "1:2:3: 4: 5: "
$ln = $line -split ":"
$ln
output:
1
2
3
4
5
The .Net System.String.Split method does not have an overload that takes a single parameter that is a string. It also does not understand regex.
What is happening is that powershell is taking the string you are passing in and converting it to an array of characters. It is essentially splitting at the following characters :
, \
, s
, +
When you use ": "
as the delimiter, I would imagine you got results like
1
2
3
4
5
That is because without specifying a string split option to the .Net method, it will include empty strings that it finds between adjacent separators.
The string split method takes a character array argument (not a string). If you specify multiple characters it will split on any instance of any of those characters.