mirror of
https://gitee.com/johng/gf
synced 2026-06-07 10:22:11 +08:00
gtest updates
This commit is contained in:
@ -10,26 +10,9 @@
|
||||
package gregex
|
||||
|
||||
import (
|
||||
"gitee.com/johng/gf/g/container/gmap"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// 缓存对象,主要用于缓存底层regx对象
|
||||
var regxCache = gmap.NewStringInterfaceMap()
|
||||
|
||||
// 根据pattern生成对应的regexp正则对象
|
||||
func getRegexp(pattern string) (*regexp.Regexp, error) {
|
||||
if v := regxCache.Get(pattern); v != nil {
|
||||
return v.(*regexp.Regexp), nil
|
||||
}
|
||||
if r, err := regexp.Compile(pattern); err == nil {
|
||||
regxCache.Set(pattern, r)
|
||||
return r, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// 转移正则规则字符串,例如:Quote(`[foo]`) 返回 `\[foo\]`
|
||||
func Quote(s string) string {
|
||||
return regexp.QuoteMeta(s)
|
||||
|
||||
46
g/string/gregex/gregex_cache.go
Normal file
46
g/string/gregex/gregex_cache.go
Normal file
@ -0,0 +1,46 @@
|
||||
// Copyright 2019 gf Author(https://gitee.com/johng/gf). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://gitee.com/johng/gf.
|
||||
|
||||
package gregex
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// 缓存对象,主要用于缓存底层regx对象
|
||||
var (
|
||||
regexMu = sync.RWMutex{}
|
||||
regexMap = make(map[string]*regexp.Regexp)
|
||||
)
|
||||
|
||||
// 根据pattern生成对应的regexp正则对象
|
||||
func getRegexp(pattern string) (*regexp.Regexp, error) {
|
||||
if r := getCache(pattern); r != nil {
|
||||
return r, nil
|
||||
}
|
||||
if r, err := regexp.Compile(pattern); err == nil {
|
||||
setCache(pattern, r)
|
||||
return r, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// 获得正则缓存对象
|
||||
func getCache(pattern string) (regex *regexp.Regexp) {
|
||||
regexMu.RLock()
|
||||
regex = regexMap[pattern]
|
||||
regexMu.RUnlock()
|
||||
return
|
||||
}
|
||||
|
||||
// 设置正则缓存对象
|
||||
func setCache(pattern string, regex *regexp.Regexp) {
|
||||
regexMu.Lock()
|
||||
regexMap[pattern] = regex
|
||||
regexMu.Unlock()
|
||||
}
|
||||
Reference in New Issue
Block a user