Merge pull request #815 from tikrgo/camelcaseConvert

This commit is contained in:
John Guo
2020-07-25 11:07:51 +08:00
committed by GitHub
2 changed files with 56 additions and 0 deletions

View File

@ -14,6 +14,7 @@
// | DelimitedScreamingCase(s, '.') | ANY.KIND.OF.STRING |
// | CamelCase(s) | AnyKindOfString |
// | CamelLowerCase(s) | anyKindOfString |
// | SnakeFirstUpperCase(RGBCodeMd5) | rgb_code_md5 |
package gstr
@ -25,6 +26,9 @@ import (
var (
numberSequence = regexp.MustCompile(`([a-zA-Z])(\d+)([a-zA-Z]?)`)
numberReplacement = []byte(`$1 $2 $3`)
firstCamelCaseStart = regexp.MustCompile(`([A-Z]+)([A-Z]?[_a-z\d]+)|$`)
firstCamelCaseEnd = regexp.MustCompile(`([\w\W]*?)([_]?[A-Z]+)$`)
)
// CamelCase converts a string to CamelCase.
@ -53,6 +57,35 @@ func SnakeScreamingCase(s string) string {
return DelimitedScreamingCase(s, '_', true)
}
// SnakeFirstUpperCase converts a string from RGBCodeMd5 to rgb_code_md5.
// The length of word should not be too long
// TODO for efficiency should change regexp to traversing string in future
func SnakeFirstUpperCase(word string, underscore ...string) string {
replace := "_"
if len(underscore) > 0 {
replace = underscore[0]
}
m := firstCamelCaseEnd.FindAllStringSubmatch(word, 1)
if len(m) > 0 {
word = m[0][1] + replace + TrimLeft(ToLower(m[0][2]), replace)
}
for {
m := firstCamelCaseStart.FindAllStringSubmatch(word, 1)
if len(m) > 0 && m[0][1] != "" {
w := strings.ToLower(m[0][1])
w = string(w[:len(w)-1]) + replace + string(w[len(w)-1])
word = strings.Replace(word, m[0][1], w, 1)
} else {
break
}
}
return TrimLeft(word, replace)
}
// KebabCase converts a string to kebab-case
func KebabCase(s string) string {
return DelimitedCase(s, '-')

View File

@ -170,3 +170,26 @@ func Test_DelimitedScreamingCase(t *testing.T) {
}
}
}
func TestSnakeFirstUpperCase(t *testing.T) {
cases := [][]string{
{"RGBCodeMd5", "rgb_code_md5"},
{"testCase", "test_case"},
{"Md5", "md5"},
{"userID", "user_id"},
{"RGB", "rgb"},
{"RGBCode", "rgb_code"},
{"_ID", "id"},
{"User_ID", "user_id"},
{"user_id", "user_id"},
{"md5", "md5"},
}
for _, i := range cases {
in := i[0]
out := i[1]
result := gstr.SnakeFirstUpperCase(in)
if result != out {
t.Error("'" + result + "' != '" + out + "'")
}
}
}