Created
December 10, 2017 15:54
-
-
Save mrcook/f5cf37da87d56ae88c767a6ce9d8db51 to your computer and use it in GitHub Desktop.
Go: Convert CamelCase strings to snake_case, with golang
This file contains hidden or 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
// Go Playground: https://play.golang.org/p/RwyPCkRi1S | |
package main | |
import ( | |
"fmt" | |
"regexp" | |
"strings" | |
) | |
var exp = regexp.MustCompile("([a-z0-9])([A-Z0-9])") | |
func toSnakeCase(s string) string { | |
return strings.ToLower(exp.ReplaceAllString(s, "${1}_${2}")) | |
} | |
func main() { | |
// examples for "normal" strings | |
fmt.Println(toSnakeCase("CamelCase")) | |
fmt.Println(toSnakeCase("ExampleNumber2")) | |
fmt.Println(toSnakeCase("My3rdProject")) | |
// examples that perhaps don't work as expected | |
fmt.Println(toSnakeCase("UPPERCase")) | |
fmt.Println(toSnakeCase("GO2")) | |
fmt.Println(toSnakeCase("A2B")) | |
} | |
// camel_case | |
// example_number_2 | |
// my_3rd_project | |
// uppercase | |
// go2 | |
// a2_b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment