PageRenderTime 39ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/src/nova/utils/regex.cc

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