Skip to content

Instantly share code, notes, and snippets.

@vermotr
Forked from regeda/underscore.go
Last active November 25, 2021 08:32
Show Gist options
  • Save vermotr/dd9cfe74169234ef7380e8f32a8fbce9 to your computer and use it in GitHub Desktop.
Save vermotr/dd9cfe74169234ef7380e8f32a8fbce9 to your computer and use it in GitHub Desktop.
Convert CamelCase to underscore in golang
package main
import (
"fmt"
"regexp"
"strings"
)
var camel = regexp.MustCompile("(^[^A-Z0-9]*|[A-Z0-9]*)([A-Z0-9][^A-Z]+|$)")
func underscore(s string) string {
var a []string
for _, sub := range camel.FindAllStringSubmatch(s, -1) {
if sub[1] != "" {
a = append(a, sub[1])
}
if sub[2] != "" {
a = append(a, sub[2])
}
}
return strings.ToLower(strings.Join(a, "_"))
}
func main() {
fmt.Println(
underscore("ILoveGoAndJSONSoMuch"),
underscore("CamelCase"),
underscore("Camel"),
underscore("CAMEL"),
underscore("camel"),
underscore("BIGCase"),
underscore("SmallCASE"),
underscore("Camel1"),
underscore("BIGCase1"),
underscore("BC1"),
)
}
@noodlensk
Copy link

underscore("my_case1") will return 1

@carldunham
Copy link

underscore("mrT") returns "T"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment