forked from reddit/mcsauna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexp.go
47 lines (40 loc) · 1010 Bytes
/
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
package main
import (
"errors"
"regexp"
)
type RegexpKey struct {
OriginalRegexp string
CompiledRegexp *regexp.Regexp
Name string
}
func NewRegexpKey(re string, name string) (regexp_key *RegexpKey, err error) {
r := &RegexpKey{}
compiled_regexp, err := regexp.Compile(re)
if err != nil {
return r, err
}
r.OriginalRegexp = re
r.CompiledRegexp = compiled_regexp
r.Name = name
return r, nil
}
type RegexpKeys struct {
regexp_keys []*RegexpKey
}
func NewRegexpKeys() *RegexpKeys {
return &RegexpKeys{}
}
func (r *RegexpKeys) Add(regexp_key *RegexpKey) {
r.regexp_keys = append(r.regexp_keys, regexp_key)
}
// Match finds the first regexp that a key matches and returns either its
// associated name, or the original regex string used in its compilation
func (r *RegexpKeys) Match(key string) (string, error) {
for _, re := range r.regexp_keys {
if re.CompiledRegexp.Match([]byte(key)) {
return re.Name, nil
}
}
return "", errors.New("Could not match key to regex.")
}