From a3cb4a6ae8959ad10984e001fa3389cbcc8a64e6 Mon Sep 17 00:00:00 2001 From: botphp Date: Wed, 22 Jul 2020 16:15:06 +0800 Subject: [PATCH] =?UTF-8?q?=E9=A9=BC=E5=B3=B0=E8=BD=AC=E6=8D=A2=E4=B8=8B?= =?UTF-8?q?=E5=88=92=E7=BA=BF=E6=97=B6=EF=BC=8C=E4=B8=8D=E8=BF=9E=E7=BB=AD?= =?UTF-8?q?=E5=A4=A7=E5=86=99=E5=AD=97=E6=AF=8D=E9=A6=96=E4=BD=8D=E5=8A=A0?= =?UTF-8?q?=E4=B8=8B=E5=88=92=E7=BA=BF=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- text/gstr/gstr_case.go | 30 ++++++++++++++++++++++++++++++ text/gstr/gstr_z_unit_case_test.go | 23 +++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/text/gstr/gstr_case.go b/text/gstr/gstr_case.go index b5b3b560e..79d4eb3cc 100644 --- a/text/gstr/gstr_case.go +++ b/text/gstr/gstr_case.go @@ -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, '-') diff --git a/text/gstr/gstr_z_unit_case_test.go b/text/gstr/gstr_z_unit_case_test.go index 4c9298658..f9df4fe6e 100644 --- a/text/gstr/gstr_z_unit_case_test.go +++ b/text/gstr/gstr_z_unit_case_test.go @@ -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 + "'") + } + } +}