From 5262c1922b5d20b9f40a01579cfcff0351d21195 Mon Sep 17 00:00:00 2001 From: GrĂ©goire DuchĂȘne Date: Sat, 7 Oct 2023 16:06:00 +0100 Subject: Add ParseStringRegexp --- flag.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'flag.go') 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] { -- cgit v1.2.3-70-g09d2