Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect CamelCase using Powershell

I would like to split song names that are in the form ArtistTitle so that they end up as Artist - Title

Is there a way in Powershell to detect the CamelCase boundary and perform the replacement? This should only affect the first case boundary and ignore the rest.

like image 293
KalenGi Avatar asked Jan 25 '26 18:01

KalenGi


1 Answers

You can use a case sensitive regular expression to split the string right before any upper case character, remove empty elements and then join what's left with a dash:

PS> 'ArtistTitle' -csplit '(?=[A-Z])' -ne '' -join '-'
Artist-Title

To split just the first word, use the second parameter of the Split operator (Max-substrings) to specifys the maximum number of substrings returned. See the about_Split help topic for more information:

PS> 'ArtistVeryLongAlbumTitle' -csplit '(?=[A-Z])',3  -ne '' -join '-'
Artist-VeryLongAlbumTitle

UPDATE: I was able to make the command shorter by using a regex pattern that doesn't split an uppercase char if it is the first one (at the beginning of the string) so an empty item is not created:

PS>  'ArtistVeryLongAlbumTitle' -csplit '(?<!^)(?=[A-Z])',2 -join '-'
Artist-VeryLongAlbumTitle
like image 74
Shay Levy Avatar answered Jan 28 '26 22:01

Shay Levy