mirror of
https://gitee.com/johng/gf
synced 2026-06-06 16:21:40 +08:00
将正则移到全局提高效率
This commit is contained in:
@ -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])
|
||||
|
||||
Reference in New Issue
Block a user