How to convert Camel case string to snake case

Issue

I have a string

str := "IGotInternAtGeeksForGeeks"

I try to convert it in to

str = "i_got_intern_at_geeks_for_geeks"

Solution

Try this,

import (
    "fmt"
    "strings"
    "regexp"
)

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

Run:

func main() {   
    fmt.Println(ToSnakeCase("IGotInternAtGeeksForGeeks"))
}

Output:

i_got_intern_at_geeks_for_geeks

NOTE: This will not work for many non-English languages.

Answered By – Tenusha Guruge

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.