2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2019-01-31 13:00:17 +08:00
|
|
|
//
|
|
|
|
// 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,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2019-01-31 13:00:17 +08:00
|
|
|
|
|
|
|
package gregex
|
|
|
|
|
|
|
|
import (
|
2019-06-19 09:06:52 +08:00
|
|
|
"regexp"
|
|
|
|
"sync"
|
2019-01-31 13:00:17 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2019-06-19 09:06:52 +08:00
|
|
|
regexMu = sync.RWMutex{}
|
|
|
|
// Cache for regex object.
|
2020-03-17 22:23:29 +08:00
|
|
|
// Note that:
|
|
|
|
// 1. It uses sync.RWMutex ensuring the concurrent safety.
|
|
|
|
// 2. There's no expiring logic for this map.
|
2019-06-19 09:06:52 +08:00
|
|
|
regexMap = make(map[string]*regexp.Regexp)
|
2019-01-31 13:00:17 +08:00
|
|
|
)
|
|
|
|
|
2019-04-23 14:15:12 +08:00
|
|
|
// getRegexp returns *regexp.Regexp object with given <pattern>.
|
|
|
|
// It uses cache to enhance the performance for compiling regular expression pattern,
|
|
|
|
// which means, it will return the same *regexp.Regexp object with the same regular
|
|
|
|
// expression pattern.
|
2020-03-04 17:29:23 +08:00
|
|
|
//
|
|
|
|
// It is concurrent-safe for multiple goroutines.
|
|
|
|
func getRegexp(pattern string) (regex *regexp.Regexp, err error) {
|
|
|
|
// Retrieve the regular expression object using reading lock.
|
2019-06-19 09:06:52 +08:00
|
|
|
regexMu.RLock()
|
|
|
|
regex = regexMap[pattern]
|
|
|
|
regexMu.RUnlock()
|
2020-03-04 17:29:23 +08:00
|
|
|
if regex != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// If it does not exist in the cache,
|
|
|
|
// it compiles the pattern and creates one.
|
|
|
|
regex, err = regexp.Compile(pattern)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Cache the result object using writing lock.
|
2019-06-19 09:06:52 +08:00
|
|
|
regexMu.Lock()
|
|
|
|
regexMap[pattern] = regex
|
|
|
|
regexMu.Unlock()
|
2020-03-04 17:29:23 +08:00
|
|
|
return
|
2019-01-31 13:00:17 +08:00
|
|
|
}
|