Friday, June 17, 2011

Splitting Pascal-Cased names in PowerShell

Something I needed to whip up recently, now slightly more polished. Starting with Jon Galloway's Splitting Camel Case with RegEx, and transposing to PowerShell's built-in regex syntax, the core operation becomes like

where we have to use the case sensitive -creplace operator to be able to insert spaces before capital letters. This outputs

Zomg
Wtf
Bbq

Wrapping it up into a function that handles a general batch of strings or things looks like this

so we can do this:

>PascalSplit @("ZomgWtfBbq", "ShazBot")
Zomg
Wtf
Bbq
Shaz
Bot
>

flattening the string array as we go (there is probably a better way to do that, but this works).

Following the link to James "poprhythm" Kolpack's enhancement, we can upgrade the simple function with his look-behind extensions to handle TLAs in names:

which we can test with

>PascalSplit LearnWCFInSixEasyMonths
Learn
WCF
In
Six
Easy
Months
>$a = PascalSplit @("ZomgWtfBbq", "ShazBot", "LearnWCFInSixEasyMonths")
>$a
Zomg
Wtf
Bbq
Shaz
Bot
Learn
WCF
In
Six
Easy
Months
>$a.Length
11
>

No comments :