matches_regexp.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2011 Aaron Jacobs. All Rights Reserved.
  2. // Author: aaronjjacobs@gmail.com (Aaron Jacobs)
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package oglematchers
  16. import (
  17. "errors"
  18. "fmt"
  19. "reflect"
  20. "regexp"
  21. )
  22. // MatchesRegexp returns a matcher that matches strings and byte slices whose
  23. // contents match the supplied regular expression. The semantics are those of
  24. // regexp.Match. In particular, that means the match is not implicitly anchored
  25. // to the ends of the string: MatchesRegexp("bar") will match "foo bar baz".
  26. func MatchesRegexp(pattern string) Matcher {
  27. re, err := regexp.Compile(pattern)
  28. if err != nil {
  29. panic("MatchesRegexp: " + err.Error())
  30. }
  31. return &matchesRegexpMatcher{re}
  32. }
  33. type matchesRegexpMatcher struct {
  34. re *regexp.Regexp
  35. }
  36. func (m *matchesRegexpMatcher) Description() string {
  37. return fmt.Sprintf("matches regexp \"%s\"", m.re.String())
  38. }
  39. func (m *matchesRegexpMatcher) Matches(c interface{}) (err error) {
  40. v := reflect.ValueOf(c)
  41. isString := v.Kind() == reflect.String
  42. isByteSlice := v.Kind() == reflect.Slice && v.Elem().Kind() == reflect.Uint8
  43. err = errors.New("")
  44. switch {
  45. case isString:
  46. if m.re.MatchString(v.String()) {
  47. err = nil
  48. }
  49. case isByteSlice:
  50. if m.re.Match(v.Bytes()) {
  51. err = nil
  52. }
  53. default:
  54. err = NewFatalError("which is not a string or []byte")
  55. }
  56. return
  57. }