stringmatches.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. __author__ = "Chris Rose"
  2. __copyright__ = "Copyright 2011 hamcrest.org"
  3. __license__ = "BSD, see License.txt"
  4. import re
  5. import six
  6. from hamcrest.core.base_matcher import BaseMatcher
  7. from hamcrest.core.helpers.hasmethod import hasmethod
  8. class StringMatchesPattern(BaseMatcher):
  9. def __init__(self, pattern):
  10. self.pattern = pattern
  11. def describe_to(self, description):
  12. description.append_text("a string matching '") \
  13. .append_text(self.pattern.pattern) \
  14. .append_text("'")
  15. def _matches(self, item):
  16. return self.pattern.search(item) is not None
  17. def matches_regexp(pattern):
  18. """Matches if object is a string containing a match for a given regular
  19. expression.
  20. :param pattern: The regular expression to search for.
  21. This matcher first checks whether the evaluated object is a string. If so,
  22. it checks if the regular expression ``pattern`` matches anywhere within the
  23. evaluated object.
  24. """
  25. if isinstance(pattern, six.string_types):
  26. pattern = re.compile(pattern)
  27. return StringMatchesPattern(pattern)