On my new project, I needed to split a method name up into its constituent parts.
For Ruby programmers, this is easy: just split on underscores. For us .NET programmers, we need something a little fancier since we like to SquashOurMethodNamesTogetherLikeThis
.
Here’s a little regular expression that can do exactly that:
(?<!^)(?=[A-Z])
That basically says to match right before every capital letter unless the capital letter is at the beginning of the string.
You can use the Regex.Split method to do the actual work of turning the method name into a string array:
Regex splitter = new Regex(@"(?<!^)(?=[A-Z])"); string[] words = splitter.Split(methodName);
My friend, Michael Kennedy, demoed in class recently how to use LINQPad to test regular expressions. It came in really handy while working on this:
I really need to click that “Activate Autocompletion” button so I can give Joseph Albahari the money he deserves for creating such a useful tool.
By the way, I used to think that “camel case” was for words like “camelCase” and “pascal case” was for words like “PascalCase”, but Wikipedia doesn’t make that distinction.