Skip to content

Instantly share code, notes, and snippets.

@geekKeen
Created July 8, 2017 10:09
Show Gist options
  • Save geekKeen/3af1200b8132c70839912f09803643fc to your computer and use it in GitHub Desktop.
Save geekKeen/3af1200b8132c70839912f09803643fc to your computer and use it in GitHub Desktop.
Code Collections
import re
_camelcase_re = re.compile(r'([A-Z]+)(?=[a-z0-9])')
def camel_to_snake_case(name):
def _join(match):
word = match.group()
if len(word) > 1:
return ('_%s_%s' % (word[:-1], word[-1])).lower()
return '_' + word.lower()
return _camelcase_re.sub(_join, name).lstrip('_')
if __name__ == "__main__":
name = "HTMLparser"
print camel_to_snake_case(name) # html_parser
@geekKeen
Copy link
Author

geekKeen commented Jul 8, 2017

Python re 模块的使用 将驼峰命名转为Python的命名方式

Questions:

  • re.sub 的使用, sub中使用函数是如何解析替换的?
  • regular express (?=...)代表什么含义?
  • 为什么需要以 _ 开头, 结果又去掉?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment