.NET - How can you split a "caps" delimited string into an array?
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 ")
Regex.Replace("ThisIsMyCapsDelimitedString", "(\\B[A-Z])", " $1")
Great answer, MizardX! I tweaked it slightly to treat numerals as separate words, so that "AddressLine1" would become "Address Line 1" instead of "Address Line1":
Regex.Replace(s, "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 ")
Just for a little variety... Here's an extension method that doesn't use a regex.
public static class CamelSpaceExtensions
{
public static string SpaceCamelCase(this String input)
{
return new string(Enumerable.Concat(
input.Take(1), // No space before initial cap
InsertSpacesBeforeCaps(input.Skip(1))
).ToArray());
}
private static IEnumerable<char> InsertSpacesBeforeCaps(IEnumerable<char> input)
{
foreach (char c in input)
{
if (char.IsUpper(c))
{
yield return ' ';
}
yield return c;
}
}
}
Grant Wagner's excellent comment aside:
Dim s As String = RegularExpressions.Regex.Replace("ThisIsMyCapsDelimitedString", "([A-Z])", " $1")