Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python function to convert camel case to snake case [duplicate]

Tags:

python

regex

I managed to cobble together a python function using regular expressions to convert camel to snake case and it works for all my test cases, yet I still have a couple questions.

1) What is each of the three statements actually doing?

import re

test_cases = list()
test_cases.append('camelCase')
test_cases.append('camelCaseCase')
test_cases.append('camel2Case')
test_cases.append('camel12Case')
test_cases.append('camel12Case')
test_cases.append('camelCaseURL')
test_cases.append('camel2CaseURL')
test_cases.append('camel12CaseURL')
test_cases.append('camel12Case2URL')
test_cases.append('camel12Case12URL')
test_cases.append('CamelCase')
test_cases.append('CamelCaseCase')
test_cases.append('URLCamelCase')


def camel_to_snake(string):
    string = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string)
    string = re.sub('(.)([0-9]+)', r'\1_\2', string)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', string).lower()


for string in test_cases:
    print(string + ' -> ' + camel_to_snake(string))

Which results in:

camelCase -> camel_case
camelCaseCase -> camel_case_case
camel2Case -> camel_2_case
camel12Case -> camel_12_case
camel12Case -> camel_12_case
camelCaseURL -> camel_case_url
camel2CaseURL -> camel_2_case_url
camel12CaseURL -> camel_12_case_url
camel12Case2URL -> camel_12_case_2_url
camel12Case12URL -> camel_12_case_12_url
CamelCase -> camel_case
CamelCaseCase -> camel_case_case
URLCamelCase -> url_camel_case
like image 231
user1507844 Avatar asked Sep 18 '26 02:09

user1507844


1 Answers

To answer your second question first, this seems like a perfectly reasonable way to accomplish this task but it might not be as maintainable as other approaches since it can be kind of difficult to figure out how it works.

Here is a breakdown of what each line does:

  • string = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string)
    Adds an underscore immediately before every single uppercase character that is followed by one or more lowercase character, except at the beginning of the string.

  • string = re.sub('(.)([0-9]+)', r'\1_\2', string)
    Adds an underscore immediately before any group of consecutive digits, except at the beginning of the string.

  • return re.sub('([a-z0-9])([A-Z])', r'\1_\2', string).lower()
    Adds an underscore immediately before any uppercase character that has a lowercase character or digit before it, and converts the whole string to lowercase and returns.

like image 55
Andrew Clark Avatar answered Sep 19 '26 14:09

Andrew Clark