Created
May 26, 2020 07:58
-
-
Save 17twenty/bc8e7153f0e76670ab4e8d4fe016db2c to your computer and use it in GitHub Desktop.
Snake To Camel and Camel To Snake Case In Go Golang
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
package main | |
import ( | |
"fmt" | |
"regexp" | |
"strings" | |
) | |
// Regex | |
var link = regexp.MustCompile("(^[A-Za-z])|_([A-Za-z])") | |
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)") | |
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])") | |
func SnakeToCamelCase(str string) string { | |
return link.ReplaceAllStringFunc(str, func(s string) string { | |
return strings.ToUpper(strings.Replace(s, "_", "", -1)) | |
}) | |
} | |
func CamelToSnakeCase(str string) string { | |
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}") | |
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}") | |
return strings.ToLower(snake) | |
} |
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
func main() { | |
fmt.Println(SnakeToCamelCase("blo_bla_Di_bla")) | |
fmt.Println(CamelToSnakeCase("MuzTouchesHisPeePee")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment