将正则移到全局提高效率

This commit is contained in:
botphp
2020-07-24 09:48:51 +08:00
parent a3cb4a6ae8
commit 1250b33220

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.
@ -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])