驼峰转换下划线时,不连续大写字母首位加下划线规范

This commit is contained in:
botphp
2020-07-22 16:15:06 +08:00
parent 0627ab81d6
commit a3cb4a6ae8
2 changed files with 53 additions and 0 deletions

View File

@ -53,6 +53,36 @@ 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
func SnakeFirstUpperCase(word string, underscore ...string) string {
replace := "_"
if len(underscore) > 0 {
replace = underscore[0]
}
r := regexp.MustCompile(`([\w\W]*?)([_]?[A-Z]+)$`)
m := r.FindAllStringSubmatch(word, 1)
if len(m) > 0 {
word = m[0][1] + replace + TrimLeft(ToLower(m[0][2]), replace)
}
r = regexp.MustCompile(`([A-Z]+)([A-Z]?[_a-z\d]+)|$`)
for {
m := r.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 + "'")
}
}
}