forked from robertkrimen/otto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexp.go
82 lines (73 loc) · 1.41 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package regexp
import (
"log"
"github.com/kirillDanshin/go-pcre"
"github.com/kirillDanshin/myutils"
)
const delim = `/`
type Regexp struct {
re *pcre.Regexp
}
type Matcher struct {
*pcre.Matcher
}
func MustCompile(pattern string) *Regexp {
r, err := CompileParse(pattern)
if err != nil {
panic(err)
}
return r
}
func CompileParse(pattern string) (*Regexp, error) {
regs.RLock()
if re, ok := regs.cache[pattern]; ok {
regs.RUnlock()
return &Regexp{
re: re,
}, nil
}
regs.RUnlock()
re, err := pcre.CompileParse(pattern)
if err != nil {
log.Printf("Otto Regexp error: %s", err)
return nil, err
}
regs.Lock()
regs.cache[pattern] = &re
regs.Unlock()
return &Regexp{
re: &re,
}, nil
}
func Compile(pattern, flags string) (*Regexp, error) {
cacheKey := myutils.Concat(pattern, delim, flags)
regs.RLock()
if re, ok := regs.cache[cacheKey]; ok {
regs.RUnlock()
return &Regexp{
re: re,
}, nil
}
regs.RUnlock()
_, flagC := pcre.ParseFlags(flags)
re, err := pcre.Compile(pattern, flagC)
if err != nil {
p := UnescapeUnicode(pattern)
re, unquotedErr := pcre.Compile(p, flagC)
if unquotedErr == nil {
return &Regexp{
re: &re,
}, nil
} else {
log.Printf("debug: pattern=[ %q ]\n\terr=[%s]\n\n", p, unquotedErr)
}
log.Printf("Otto Regexp error: %s\n\n", err)
return nil, err
}
regs.Lock()
regs.cache[cacheKey] = &re
regs.Unlock()
return &Regexp{
re: &re,
}, nil
}