Author Posts

November 23, 2016 at 10:08 am

It's probably something noobish but I'm wondering why this happens.

Example Code:

$text = "12345`r`n6789`r`n"

$textSplit = $text.Split("`r`n")

$textSplit.Length

Why does this genereate a length of 5?

I would expect this to be 3.
First Line: 12345
Second Line: 6789
Third Line: Empty due to the CRLF at the end.

November 23, 2016 at 10:12 am

Try this:

$textSplit | Foreach-Object -Process { "'$($_)'" }

There you will see it's more a count than a length. 😉

If you use Split("`r`n") the string will be splitted on all `r's AND `n's.

November 23, 2016 at 10:16 am

Yes the textSplit will be a count of lines, the question is why the split generate the empty lines.

So.
12345
"
6789
"
"

Would expect it to be:
12345
6789
"

November 23, 2016 at 10:17 am

... If you use Split("`r`n") the string will be splitted on all `r's AND `n's.

November 23, 2016 at 10:32 am

Hmm, ok then I would need to remove the CR from the string first (in the real world scenario).
Since I don't know if it will be there or not.
Seems that depending on system/program that is used it's either CR & LF or just LF that get added.

November 23, 2016 at 10:52 am

Hmm, ok then I would need to remove the CR from the string first (in the real world scenario).
Since I don't know if it will be there or not.

Sounds like :-/ But as you are aware off this now it's not a big deal. 😉

Seems that depending on system/program that is used it's either CR & LF or just LF that get added.

I guess that's a little bit a Windows Unix thing.

November 23, 2016 at 11:09 am

You can use -split with proper regex

 D:\> $textSplit = $text -split "[`r`n]+"
 D:\> $textSplit.count
3
 D:\> $textSplit
12345
6789

November 23, 2016 at 4:29 pm

The easy solution is to use the '-split' operator, which splits the string on any whitespace, including carriage returns, line feeds, spaces, etc.

c:\> $text = "12345`r`n6789`r`n"
c:\> $textSplit = -split $text
c:\> $textSplit.Length
2
c:\> $textSplit
12345
6789
c:\> 

November 24, 2016 at 1:49 pm

Yep, it seems it's best to use -split and either using the defaults or the earlier regex example.

Thanks for the input guys.