Splitting Texts by Fixed Width

by May 18, 2019

Let’s assume you need to split a text using a fixed width. For example, if you needed the first 5 character of a text, plus the remainder, how would you do this?

Most PowerShell users would probably use string methods like these:

$text = 'ID12:Here is the text'
$prefix = $text.Substring(0,5)
$suffix = $text.Substring(5)
$prefix
$suffix

Of course, if you had a split character such as “:”, you could also go with this:

$prefix, $suffix = 'ID12:Here is the text' -split ':'
$prefix
$suffix 

However, this would consume the split character plus it can produce more than two parts. And it is not what the job was: to split a text using a fixed WIDTH. Yet you still can use the -split operator:

$prefix, $suffix = 'ID12:Here is the text' -split '(?<=^.{5})'
$prefix
$suffix  

The regex construct “(?<=XXX)” is a so-called “look behind” and not consumed. “^” represents the text start, and “.” represents any character. As you may have guessed, “{5}” qualifies how often the placeholder must occur, so essentially this regex splits the first 5 characters from the rest of the text and always returns two chunks (provided the text is at least 6 characters long).


psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!