summaryrefslogtreecommitdiff
path: root/flag.go
diff options
context:
space:
mode:
Diffstat (limited to 'flag.go')
-rw-r--r--flag.go19
1 files changed, 19 insertions, 0 deletions
diff --git a/flag.go b/flag.go
index 7255802..7db895b 100644
--- a/flag.go
+++ b/flag.go
@@ -4,15 +4,22 @@
package core
import (
+ "errors"
"flag"
"fmt"
"os"
+ "regexp"
"strconv"
"strings"
"sync/atomic"
"time"
)
+// ErrStringRegexpNoMatch is an error wrapped and returned by functions
+// created by ParseStringRegexp if the string passed did not match the
+// regular expression used.
+var ErrStringRegexpNoMatch = errors.New("string did not match regexp")
+
// Flag works like other flag.FlagSet methods, except it is generic. The
// passed ParseFunc will be used to parse raw arguments into a useful T
// value. A valid *T is returned for use by the caller.
@@ -182,6 +189,18 @@ func ParseStringEnum(values ...string) ParseFunc[string] {
}
}
+// ParseStringRegexp returns a ParseFunc that will return the string
+// passed if it matches the regular expression.
+func ParseStringRegexp(r *regexp.Regexp) ParseFunc[string] {
+ err := fmt.Errorf("%w %q", ErrStringRegexpNoMatch, r)
+ return func(s string) (string, error) {
+ if !r.MatchString(s) {
+ return "", err
+ }
+ return s, nil
+ }
+}
+
// ParseStringerEnum returns a ParseFunc that will return the first
// value having a string value matching the string passed.
func ParseStringerEnum[T fmt.Stringer](values ...T) ParseFunc[T] {