-
-
Save vermotr/dd9cfe74169234ef7380e8f32a8fbce9 to your computer and use it in GitHub Desktop.
Convert CamelCase to underscore in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"), | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
underscore("mrT") returns "T"