Golang Convert String into Snake Case

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"))
}

C:\golang\coding>go run example125.go
japan_canada_australia
japan_canada_australia
japan_canada_australia
japan125_canada130_australia150

C:\golang\coding>

Thanks for reading. Please leave your valuable feedback and comments.

* Required Fields