Skip to content

Instantly share code, notes, and snippets.

@stoewer
Last active March 29, 2022 16:59
Show Gist options
  • Save stoewer/fbe273b711e6a06315d19552dd4d33e6 to your computer and use it in GitHub Desktop.
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
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)
}
@adombeck
Copy link

@hxsf: That looks great! Do you mind adding a license to your gist?

@hxsf
Copy link

hxsf commented Sep 27, 2021

@adombeck add MIT license.

@adombeck
Copy link

@hxsf: Great, thanks a lot!

@elvizlai
Copy link

elvizlai commented Oct 16, 2021

@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

@hxsf
Copy link

hxsf commented Oct 16, 2021

@elvizlai I update the code. and it works

@abdennour
Copy link

good guys ! keep it up!
kebab case should be concluded here as well

@hxsf
Copy link

hxsf commented Jan 18, 2022

@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