Skip to content

Commit 244804c

Browse files
committed
Support regexp match filtering
1 parent 040e869 commit 244804c

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

it/filter/filter.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
// This package contains functions intended for use with [iter.Filter].
22
package filter
33

4-
import "cmp"
4+
import (
5+
"cmp"
6+
"regexp"
7+
)
58

69
// IsEven returns true when the provided integer is even.
710
func IsEven[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~int | ~int8 | ~int16 | ~int32 | ~int64](integer T) bool {
@@ -95,3 +98,9 @@ func Or[T any](filters ...func(T) bool) func(T) bool {
9598
return false
9699
}
97100
}
101+
102+
func Match[T string | []byte](pattern *regexp.Regexp) func(T) bool {
103+
return func(term T) bool {
104+
return pattern.MatchString(string(term))
105+
}
106+
}

it/filter/filter_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package filter_test
33
import (
44
"fmt"
55
"maps"
6+
"regexp"
67
"slices"
78

89
"github.com/BooleanCat/go-functional/v2/it"
@@ -129,3 +130,27 @@ func ExampleOr() {
129130
// 2
130131
// 4
131132
}
133+
134+
func ExampleMatch_string() {
135+
pattern := regexp.MustCompile(`^foo`)
136+
137+
strings := slices.Values([]string{"foobar", "barfoo"})
138+
139+
for match := range it.Filter(strings, filter.Match[string](pattern)) {
140+
fmt.Println(match)
141+
}
142+
143+
// Output: foobar
144+
}
145+
146+
func ExampleMatch_bytes() {
147+
pattern := regexp.MustCompile(`^foo`)
148+
149+
strings := slices.Values([][]byte{[]byte("foobar"), []byte("barfoo")})
150+
151+
for match := range it.Filter(strings, filter.Match[[]byte](pattern)) {
152+
fmt.Println(string(match))
153+
}
154+
155+
// Output: foobar
156+
}

0 commit comments

Comments
 (0)