Snake case to camel case and back using regular expressions and Python
Snake case and Camel case are conventions of naming variables, functions and classes. Most teams and projects prescribe a particular case in their style guides. Examples of camel case: MyClass MyClassFactory MyClassFactoryBuilder MyClassFactoryBuilderImpl myInstance myInstance2 abc patternMatcher Examples of snake case: add matrix_add diagonal_matrix_add pseudo_inverse If we want to convert back and forth between these cases, we must look for the points of interest - the word boundaries. Camel case boundaries have the first letter capitalized while the snake case word boundaries have an _. Snake case to camel case Here is a regular expression for finding out the _ and the first letter in the next word: (.*?)_([a-zA-Z]) This regex has 2 parts: (.*?) finds everything upto the _. The ‘.’ means any character. ‘*’ stands for match 0 or more instances ‘?’ stands for non-greedy match. We must use ‘?’ in the pattern because the regex engine will try to match as much as possible by default. So, if we use just (.*), the whole word will be consumed and nothing will be left for the rest of the pattern. ‘()’ stand for a group. A group is a way of saving a part of the match for later. Together, they mean that find all characters upto the first ‘_’ and capture them in a group. ([a-zA-Z]) finds the first alphabet after the _. We need this to convert to upper case for Camel case. ...