Skip to content

Instantly share code, notes, and snippets.

@bryant
Last active September 12, 2016 08:59
Show Gist options
  • Save bryant/5885822 to your computer and use it in GitHub Desktop.
Save bryant/5885822 to your computer and use it in GitHub Desktop.
CamelCase -> camel_case
import re
_endpiecere = re.compile(r"[A-Z]+$")
_camelre = re.compile(r"([A-Z]+)(?=[0-9a-z])")
def camel2underscore(camel):
camel = _endpiecere.sub(lambda m: "_" + m.group(0).lower(), camel)
def insert(match):
m = match.group(0).lower()
return "_" + (m if len(m) == 1 else m[:-1] + "_" + m[-1])
return _camelre.sub(insert, camel).lstrip("_")
if __name__ == "__main__":
def passert(a, b):
if a == b:
print "ok:", a
else:
print "FAIL:", a, "!=", b
passert(camel2underscore("SimpleCase"), "simple_case")
passert(camel2underscore("LuckyNumberS7evin"), "lucky_number_s7evin")
passert(camel2underscore("LLVMContext"), "llvm_context")
passert(camel2underscore("MarkAndSweepGC"), "mark_and_sweep_gc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment