Skip to content

camelCase to snake_case conversion - Fixes #9726 #9727

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
code modified to not use regex
  • Loading branch information
Mrk-Mzj authored Oct 5, 2023
commit 28f41df979d496f45e28102b537c44548bd46219
37 changes: 21 additions & 16 deletions strings/camel_case_to_snake_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ def camel_to_snake_case(input_str: str) -> str:
>>> camel_to_snake_case("someRandomString")
'some_random_string'

>>> camel_to_snake_case("SomeRandomString")
'some_random_string'
>>> camel_to_snake_case("SomeRandomStr#ng")
'some_random_str_ng'

>>> camel_to_snake_case("123someRandom123String123")
'123_some_random_123_string_123'
Expand All @@ -21,30 +21,35 @@ def camel_to_snake_case(input_str: str) -> str:

"""

import re

# check for invalid input type
if not isinstance(input_str, str):
msg = f"Expected string as input, found {type(input_str)}"
raise ValueError(msg)

# Replace all characters that are not letters or numbers with the underscore
snake_str = re.sub(r"[^a-zA-Z0-9]", "_", input_str)
snake_str = ""

for index, char in enumerate(input_str):
if char.isupper():
snake_str += "_" + char.lower()

# Find where lowercase meets uppercase. Insert underscore between them
snake_str = re.sub(r"([a-z])([A-Z])", r"\1_\2", snake_str).lower()
# if char is lowercase but proceeded by a digit:
elif input_str[index - 1].isdigit() and char.islower():
snake_str += "_" + char

# Find the sequence of digits at the beginning
snake_str = re.sub(r"^(\d+)", r"\1_", snake_str)
# if char is a digit proceeded by a letter:
elif input_str[index - 1].isalpha() and char.isnumeric():
snake_str += "_" + char.lower()

# Find the sequence of digits at the end
snake_str = re.sub(r"(\d+)$", r"_\1", snake_str)
# if char is not alphanumeric:
elif not char.isalnum():
snake_str += "_"

# Find where letter meets digits
snake_str = re.sub(r"([a-z])(\d+)", r"\1_\2", snake_str)
else:
snake_str += char

# Find where digits meet letter
snake_str = re.sub(r"(\d+)([a-z])", r"\1_\2", snake_str)
# remove leading underscore
if snake_str[0] == "_":
snake_str = snake_str[1:]

return snake_str

Expand Down