Skip to content

Commit 1c5b627

Browse files
committed
added inverse regex support
1 parent 78c383f commit 1c5b627

File tree

2 files changed

+83
-4
lines changed

2 files changed

+83
-4
lines changed

regex.go

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,35 @@
11
package k8seventwatcher
22

3-
import "regexp"
3+
import (
4+
"regexp"
5+
"strings"
6+
)
47

58
type Regexp struct {
6-
*regexp.Regexp
9+
regex *regexp.Regexp
10+
11+
inverseMatch bool
12+
}
13+
14+
func NewRegexp(pattern string) (*Regexp, error) {
15+
r := &Regexp{}
16+
17+
// Is this an inverse match?
18+
if strings.HasPrefix(pattern, "!") {
19+
r.inverseMatch = true
20+
pattern = pattern[1:]
21+
} else {
22+
r.inverseMatch = false
23+
}
24+
25+
var err error
26+
27+
r.regex, err = regexp.Compile(pattern)
28+
if err != nil {
29+
return nil, err
30+
}
31+
32+
return r, nil
733
}
834

935
func (r *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {
@@ -13,14 +39,37 @@ func (r *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {
1339
return err
1440
}
1541

16-
(*r).Regexp, err = regexp.Compile(regexString)
42+
newRegex, err := NewRegexp(regexString)
1743
if err != nil {
1844
return err
1945
}
2046

47+
r.inverseMatch = newRegex.inverseMatch
48+
r.regex = newRegex.regex
49+
2150
return nil
2251
}
2352

2453
func (r *Regexp) MarshalYAML() (interface{}, error) {
25-
return r.Regexp.String(), nil
54+
return r.String(), nil
55+
}
56+
57+
func (r *Regexp) String() string {
58+
regexString := r.regex.String()
59+
60+
if r.inverseMatch {
61+
regexString = "!" + regexString
62+
}
63+
64+
return regexString
65+
}
66+
67+
func (r *Regexp) MatchString(value string) bool {
68+
matches := r.regex.MatchString(value)
69+
70+
if r.inverseMatch {
71+
matches = !matches
72+
}
73+
74+
return matches
2675
}

regex_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package k8seventwatcher
2+
3+
import "testing"
4+
5+
func TestRegexpInverse(t *testing.T) {
6+
regexString := "hello"
7+
regex, err := NewRegexp(regexString)
8+
if err != nil {
9+
t.Fatal(err)
10+
}
11+
12+
if !regex.MatchString("hello123") {
13+
t.Fatal("no match")
14+
}
15+
16+
regexInverseString := "!hello"
17+
regexInverse, err := NewRegexp(regexInverseString)
18+
if err != nil {
19+
t.Fatal(err)
20+
}
21+
22+
if regexInverse.MatchString("hello123") {
23+
t.Fatal("no match")
24+
}
25+
26+
if !regexInverse.MatchString("mello123") {
27+
t.Fatal("no match")
28+
}
29+
30+
}

0 commit comments

Comments
 (0)