I want to create a function that will allow me to convert CamelCase to Title Case. This seems like a good task for regular expressions, but I am not committed to using regular expressions, if you have a better solution.
Here is my first attempt that works in most cases, but there are some issues I will get to in a few lines:
private static Regex camelSplitRegex = new Regex(@"(\S)([A-Z])");
private static String camelReplacement = "$1 $2";
public String SplitCamel(String text){
return camelSplitRegex.Replace(text, camelReplacement);
}
The regex pattern looks for a non-whitespace character (1st capture) followed by a capital letter (2nd capture). In the function, Regex.Replace
is used to insert a space between the 1st and 2nd captures.
This works fine for many examples:
SplitCamel("privateField")
returns"private Field"
SplitCamel("PublicMethod")
returns"Public Method"
SplitCamel(" LeadingSpace")
returns" Leading Space"
without inserting an extra space before "Leading", as desired.
The problem I have is when dealing with multiple consecutive capital letters.
SplitCamel("NASA")
returns "N AS A" not "N A S A"SplitCamel("C3PO")
returns "C3 PO" not "C3 P O"SplitCamel("CAPS LOCK FEVER")
returns "C AP S L OC K F EV E R" not "C A P S L O C K F E V E R"
In these cases, I believe the issue is that each capital letter is only being captured as either \S
or [A-Z]
, but cannot be \S
on one match and [A-Z]
on the next match.
My main question is, "Does the .NET regex engine has some way of supporting the same substring being used as different captures on consecutive matches?" Secondarily, is there a better way of splitting camel case?