From 1250b33220b21f994238f29c4bdb7aa130d25974 Mon Sep 17 00:00:00 2001 From: botphp Date: Fri, 24 Jul 2020 09:48:51 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86=E6=AD=A3=E5=88=99=E7=A7=BB=E5=88=B0?= =?UTF-8?q?=E5=85=A8=E5=B1=80=E6=8F=90=E9=AB=98=E6=95=88=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- text/gstr/gstr_case.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/text/gstr/gstr_case.go b/text/gstr/gstr_case.go index 79d4eb3cc..e264f1e2a 100644 --- a/text/gstr/gstr_case.go +++ b/text/gstr/gstr_case.go @@ -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. @@ -55,21 +59,20 @@ func SnakeScreamingCase(s string) string { // 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] } - r := regexp.MustCompile(`([\w\W]*?)([_]?[A-Z]+)$`) - m := r.FindAllStringSubmatch(word, 1) + m := firstCamelCaseEnd.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) + 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])