-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregexp.go
57 lines (49 loc) · 1.09 KB
/
regexp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package goutils
import (
"regexp"
"github.com/hoveychen/go-utils/gomap"
)
var (
cachedRegexp = gomap.New()
)
type Regexp struct {
*regexp.Regexp
err error
}
// CompileRegexp is the same as regexp.Compile(), except it cached all the
// compiled patterns for performance.
func CompileRegexp(pattern string) (*Regexp, error) {
re := cachedRegexp.GetOrCreate(pattern, func() interface{} {
re, err := regexp.Compile(pattern)
return &Regexp{
Regexp: re,
err: err,
}
}).(*Regexp)
if re.err != nil {
return nil, re.err
}
return re, nil
}
// MatchString is the same as regexp.MatchString(),
// except it use the cached version of compiled pattern.
func MatchString(pattern, s string) (matched bool, err error) {
re, err := CompileRegexp(pattern)
if err != nil {
return false, err
}
return re.MatchString(s), nil
}
func (r *Regexp) FindNamedStringSubmatch(s string) map[string]string {
match := r.FindStringSubmatch(s)
if match == nil {
return nil
}
ret := map[string]string{}
for i, name := range r.SubexpNames() {
if name != "" {
ret[name] = match[i]
}
}
return ret
}