Splitting Texts without Losing Anything

by Dec 26, 2012

Typically when you split a text using the -split operator or the Split() method, the split character is removed from the text:

$profile -split '\\'
C:
Users
Tobias
Documents
WindowsPowerShell
Microsoft.PowerShell_profile.ps1

If you want to keep it, make it a "look ahead" by adding "?<=". This way, PowerShell looks for the backslash, then looks "ahead" and cuts right after it:

PS> $profile -split '(?<=\\)'
C:\
Users\
Tobias\
Documents\
WindowsPowerShell\
Microsoft.PowerShell_profile.ps1

You can also make it a "look behind", so it searches for the backslash, then turns around and looks "back", cutting the text right before the backslash, again without removing it. Add a "?=" this time:

PS> $profile -split '(?=\\)'
C:
\Users
\Tobias
\Documents
\WindowsPowerShell
\Microsoft.PowerShell_profile.ps1

Twitter This Tip! ReTweet this Tip!