match_regexp_matcher.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package matchers
  2. import (
  3. "fmt"
  4. "regexp"
  5. "github.com/onsi/gomega/format"
  6. )
  7. type MatchRegexpMatcher struct {
  8. Regexp string
  9. Args []interface{}
  10. }
  11. func (matcher *MatchRegexpMatcher) Match(actual interface{}) (success bool, err error) {
  12. actualString, ok := toString(actual)
  13. if !ok {
  14. return false, fmt.Errorf("RegExp matcher requires a string or stringer.\nGot:%s", format.Object(actual, 1))
  15. }
  16. match, err := regexp.Match(matcher.regexp(), []byte(actualString))
  17. if err != nil {
  18. return false, fmt.Errorf("RegExp match failed to compile with error:\n\t%s", err.Error())
  19. }
  20. return match, nil
  21. }
  22. func (matcher *MatchRegexpMatcher) FailureMessage(actual interface{}) (message string) {
  23. return format.Message(actual, "to match regular expression", matcher.regexp())
  24. }
  25. func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual interface{}) (message string) {
  26. return format.Message(actual, "not to match regular expression", matcher.regexp())
  27. }
  28. func (matcher *MatchRegexpMatcher) regexp() string {
  29. re := matcher.Regexp
  30. if len(matcher.Args) > 0 {
  31. re = fmt.Sprintf(matcher.Regexp, matcher.Args...)
  32. }
  33. return re
  34. }