Advanced Text Splitting

by Sep 30, 2014

All PowerShell Versions

When you use the –split operator to split text, then the split text is consumed:

PS> 'Hello, this is a text, and it has commas' -split ','
Hello
 this is a text
 and it has commas

As you see, the commas are gone.

The split text can be longer than just one character. This would split at any location that has a comma plus a space:

PS> 'Hello, this is a text, and it has commas' -split ', '
Hello
this is a text
and it has commas 

And since –split expects really a regular expression, this would split at any location that is a comma and then at least one space:

PS> 'Hello,    this is a    text, and it has commas' -split ',\s{1,}'
Hello
this is a    text
and it has commas 


If you want, you can keep the split text with the results by enclosing the split text in “(?=…)”:

PS> 'Hello,    this is a    text, and it has commas' -split '(?=,\s{1,})'
Hello
,    this is a    text
, and it has commas 

Twitter This Tip! ReTweet this Tip!