diff options
| author | Grégoire Duchêne <gduchene@awhk.org> | 2023-10-07 16:06:00 +0100 |
|---|---|---|
| committer | Grégoire Duchêne <gduchene@awhk.org> | 2023-10-07 16:06:00 +0100 |
| commit | 5262c1922b5d20b9f40a01579cfcff0351d21195 (patch) | |
| tree | 0fdacfa675fa54c4508c017f3b7336bfebb19e4f /flag.go | |
| parent | ad0306e9e79df26146ee8c74531574385f461f81 (diff) | |
Add ParseStringRegexpv0.7.0
Diffstat (limited to 'flag.go')
| -rw-r--r-- | flag.go | 19 |
1 files changed, 19 insertions, 0 deletions
@@ -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] { |
