regex-partial.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #pragma once
  2. #include <regex>
  3. #include <string>
  4. enum common_regex_match_type {
  5. COMMON_REGEX_MATCH_TYPE_NONE,
  6. COMMON_REGEX_MATCH_TYPE_PARTIAL,
  7. COMMON_REGEX_MATCH_TYPE_FULL,
  8. };
  9. struct common_string_range {
  10. size_t begin;
  11. size_t end;
  12. common_string_range(size_t begin, size_t end) : begin(begin), end(end) {
  13. if (begin > end) {
  14. throw std::runtime_error("Invalid range");
  15. }
  16. }
  17. // prevent default ctor
  18. common_string_range() = delete;
  19. bool empty() const {
  20. return begin == end;
  21. }
  22. bool operator==(const common_string_range & other) const {
  23. return begin == other.begin && end == other.end;
  24. }
  25. };
  26. struct common_regex_match {
  27. common_regex_match_type type = COMMON_REGEX_MATCH_TYPE_NONE;
  28. std::vector<common_string_range> groups;
  29. bool operator==(const common_regex_match & other) const {
  30. return type == other.type && groups == other.groups;
  31. }
  32. bool operator!=(const common_regex_match & other) const {
  33. return !(*this == other);
  34. }
  35. };
  36. class common_regex {
  37. std::string pattern;
  38. std::regex rx;
  39. std::regex rx_reversed_partial;
  40. public:
  41. explicit common_regex(const std::string & pattern);
  42. common_regex_match search(const std::string & input, size_t pos, bool as_match = false) const;
  43. const std::string & str() const { return pattern; }
  44. };
  45. // For testing only (pretty print of failures).
  46. std::string regex_to_reversed_partial_regex(const std::string & pattern);