Simplify camel snippet

Remove regex with complex look-behind matching, replace with simpler string functions
This commit is contained in:
Havan Agrawal
2019-08-23 00:06:40 -07:00
committed by GitHub
parent 2aa19e8cda
commit 3ee07828d2

View File

@ -5,17 +5,17 @@ tags: string,regexp,intermediate
Converts a string to camelcase. Converts a string to camelcase.
Break the string into words and combine them capitalizing the first letter of each word, using a regexp. Break the string into words and combine them capitalizing the first letter of each word, using `title`.
`(\s|_|-)+` matches one or more spaces (`\s`), underscores (`_`) or hyphens (`-`). `re.sub` replaces these matches with single spaces.
`title` capitalizes the first letter of each word. `replace(" ", "")` removes the spaces between words.
```py ```py
import re import re
def camel(str): def camel(s):
s = re.sub(r"(\s|_|-)+","", pascal = re.sub(r"(\s|_|-)+", " ", s).title().replace(" ", "")
re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", return pascal[0].lower() + pascal[1:]
lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(),str)
)
return s[0].lower() + s[1:]
``` ```
```py ```py