Last active
March 29, 2022 16:59
-
-
Save stoewer/fbe273b711e6a06315d19552dd4d33e6 to your computer and use it in GitHub Desktop.
Convert camel case to snake case in Go http://play.golang.org/p/9ybqJat1Hr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"fmt" | |
"strings" | |
"regexp" | |
) | |
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)") | |
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])") | |
func ToSnakeCase(str string) string { | |
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}") | |
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}") | |
return strings.ToLower(snake) | |
} |
@hxsf: That looks great! Do you mind adding a license to your gist?
@adombeck add MIT license.
@hxsf: Great, thanks a lot!
@hxsf Test failed for
MyLIFEIsAwesomE
should be my_life_is_awesom_e
but got mylife_is_awesome
Japan125Canada130Australia150
should be japan125_canada130_australia150
but got japan1_2_5_canada1_3_0_australia1_5_0
@elvizlai I update the code. and it works
good guys ! keep it up!
kebab case should be concluded here as well
@abdennour just replace '_' with '-' in the code, and change the function name. I think it will work.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@hxsf looks awesome! Yeah, I forgot about additional capacity for underscores %)