bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/name/regexp.go (about)

     1  package name
     2  
     3  import (
     4  	"errors"
     5  	"regexp"
     6  )
     7  
     8  type regexpValidationConfig struct {
     9  	matcher *regexp.Regexp
    10  }
    11  
    12  // NewRegexpValidator constructs a new Validator which verifies that a name matches a specific regular expression
    13  func NewRegexpValidator(validPattern string) (Validator, error) {
    14  	if len(validPattern) == 0 {
    15  		return nil, errors.New("no validPattern provided")
    16  	}
    17  
    18  	matcher, err := regexp.Compile(validPattern)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	result := &regexpValidationConfig{matcher: matcher}
    24  	return result, nil
    25  }
    26  
    27  // IsValid returns true if the given name matches the Validators regular expression
    28  func (c *regexpValidationConfig) IsValid(name string) bool {
    29  	return c.matcher.MatchString(name)
    30  }