diff --git a/snippets/snake.md b/snippets/snake.md index b8376fe73..4aa3f83fe 100644 --- a/snippets/snake.md +++ b/snippets/snake.md @@ -5,16 +5,15 @@ tags: string,regexp,intermediate Converts a string to snake case. -Break the string into words and combine them adding `_-_` as a separator, using a regexp. +Break the string into words and combine them adding `_` as a separator, using a regexp. ```py import re def snake(str): - return re.sub(r"(\s|_|-)+","_", - re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", - lambda mo: mo.group(0).lower(),str) - ) + return '_'.join(re.sub('([A-Z][a-z]+)', r' \1', + re.sub('([A-Z]+)', r' \1', + str.replace('-', ' '))).split()).lower() ``` ```py