Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert camelCase to snake_case ignoring multiple uppercase

I would like to convert camelCase to snake_case, but ignoring multiple capitalized letters in the camelCase.
I have the following function:

re.sub(r'(?<!^)(?=[A-Z])', '_', name).upper()

This returns the following results:

abcFunction --> ABC_FUNCTION
ABCFunction --> A_B_C_FUNCTION

Is there a way to get the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

abcFunction --> ABC_FUNCTION
ABCFunction --> ABC_FUNCTION

>Solution :

import re

name = 'abcFunction'
name2 = 'ABCFunction'
def converter(name):
    name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).upper()

print(converter(name))
print(converter(name2))

Output

ABC_FUNCTION
ABC_FUNCTION
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading