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: Arrays of Arrays, Arrays of Slices, Slices of Arrays and Slices of Slices
Find capacity of Channel, Pointer and Slice
Generate a Keygen of 256 bits
How to use a mutex to define critical sections of code and fix race conditions?
How to Convert string to integer type in Go?
Golang HTML parser