PageRenderTime 45ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/reddwarf-guest/src/nova/utils/regex.cc

https://github.com/cp16net/reddwarf
C++ | 67 lines | 47 code | 14 blank | 6 comment | 5 complexity | fbd4dad7feedd9e297af58284d2af27a MD5 | raw file
Possible License(s): Apache-2.0
  1. #include "nova/utils/regex.h"
  2. #include <regex.h>
  3. #include <stdexcept>
  4. namespace nova { namespace utils {
  5. /**---------------------------------------------------------------------------
  6. *- Regex
  7. *---------------------------------------------------------------------------*/
  8. Regex::Regex(const char * pattern) {
  9. regcomp(&regex, pattern, REG_EXTENDED);
  10. }
  11. Regex::~Regex() {
  12. regfree(&regex);
  13. }
  14. RegexMatchesPtr Regex::match(const char * line, size_t max_matches) const {
  15. regmatch_t * matches = new regmatch_t[max_matches];
  16. if (regexec(&regex, line, max_matches, matches, 0) == 0) {
  17. RegexMatchesPtr ptr(new RegexMatches(line, matches, max_matches));
  18. return ptr;
  19. } else {
  20. delete[] matches;
  21. return RegexMatchesPtr();
  22. }
  23. }
  24. /**---------------------------------------------------------------------------
  25. *- RegexMatches
  26. *---------------------------------------------------------------------------*/
  27. RegexMatches::RegexMatches(const char * line, regmatch_t * matches, size_t size)
  28. : line(line), matches(matches), nmatch(size) {
  29. }
  30. RegexMatches::~RegexMatches() {
  31. delete[] matches;
  32. }
  33. bool RegexMatches::exists_at(size_t index) const {
  34. if (index < nmatch) {
  35. const regoff_t & start_index = matches[index].rm_so;
  36. return start_index >= 0;
  37. }
  38. return false;
  39. }
  40. std::string RegexMatches::get(size_t index) const {
  41. if (!exists_at(index)) {
  42. static const std::string error_msg("No match exists at given index.");
  43. throw std::out_of_range(error_msg);
  44. }
  45. const regoff_t & start_index = matches[index].rm_so;
  46. const regoff_t & end_index = matches[index].rm_eo;
  47. const regoff_t match_size = end_index - start_index;
  48. return line.substr(start_index, match_size);
  49. }
  50. std::string RegexMatches::original_line() const {
  51. return line;
  52. }
  53. } } // end of nova::utils namespace