.netregexalgorithmstringpascalcasing

.NET - How can you split a "caps" delimited string into an array?


How do I go from this string: "ThisIsMyCapsDelimitedString"

...to this string: "This Is My Caps Delimited String"

Fewest lines of code in VB.net is preferred but C# is also welcome.

Cheers!


Solution

  • I made this a while ago. It matches each component of a CamelCase name.

    /([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g
    

    For example:

    "SimpleHTTPServer" => ["Simple", "HTTP", "Server"]
    "camelCase" => ["camel", "Case"]
    

    To convert that to just insert spaces between the words:

    Regex.Replace(s, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ")
    

    If you need to handle digits:

    /([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/g
    
    Regex.Replace(s,"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))","$1 ")