Daniel Drake
Daniel Drake

Reputation: 33

Split a string in PowerShell

I heard this forum is amazing for answering the craziest questions and I have searched hi and low for an answer to my crazy question, however I cannot find an answer. So I am putting this out to the community.

I use PowerShell for my scripting needs. please Don't offer me a solution in another scripting language, I'm sure other script languages will do this, however I need this in PowerShell.

I have many strings that I need to split they are similar in nature to:

HelloWorld
HelloWorldIAmNew
HelloWorldIAmNewToScripting
ThankYouForHelpingMe

I need to split them based on Capital Letters i.e.

Hello World
Hello World I Am New
Hello World I Am New To Scripting
Thank You For Helping Me

I have a basic understanding on splitting strings, but this is harder than your average string.

Upvotes: 3

Views: 6072

Answers (2)

CB.
CB.

Reputation: 60910

Try this:

("HelloWorldIAmNewToScripting" -creplace '[A-Z]', ' $&').Trim().Split($null)
Hello
World
I
Am
New
To
Scripting

or

("HelloWorldIAmNewToScripting" -creplace '[A-Z]', ' $&').Trim()
Hello World I Am New To Scripting

Upvotes: 1

Keith Hill
Keith Hill

Reputation: 201622

Fairly simple to do using a regex with negative and positive lookahead (?=pattern) and the case-sensitive -csplit operator e.g.:

PS>  "HelloWorldIAmNewToScripting" -csplit "(?<=.)(?=[A-Z])"
Hello
World
I
Am
New
To
Scripting

Or if you want it space separated:

PS>  "$("HelloWorldIAmNewToScripting" -csplit "(?<=.)(?=[A-Z])")"
Hello World I Am New To Scripting

Upvotes: 9

Related Questions