Golang Convert String into Snake Case
Example
package main
import (
"fmt"
"regexp"
"strings"
)
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)
}
func main() {
fmt.Println(ToSnakeCase("JapanCanadaAustralia"))
fmt.Println(ToSnakeCase("JapanCanadaAUSTRALIA"))
fmt.Println(ToSnakeCase("JAPANCanadaAUSTRALIA"))
fmt.Println(ToSnakeCase("Japan125Canada130Australia150"))
}
Output
japan_canada_australia
japan_canada_australia
japan_canada_australia
japan125_canada130_australia150
Most Helpful This Week
Example: How to use TeeReader from IO Package in Golang?
How to check lowercase characters in a string in Golang?
Runtime package variables
User Defined Function Types in Golang
Strip all white spaces, tabs, newlines from a string
Get Year, Month, Day, Hour, Min and Second from current date and time.