pcre.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. ///////////////////////////////////////////////////////////////
  2. // Copyright 2015 John Maddock. Distributed under the Boost
  3. // Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_
  5. //
  6. #ifdef TEST_PCRE2
  7. #define PCRE2_STATIC
  8. #define PCRE2_CODE_UNIT_WIDTH 8
  9. #include "performance.hpp"
  10. #include <pcre2.h>
  11. #include <boost/version.hpp>
  12. #include <boost/lexical_cast.hpp>
  13. struct pcre_regex : public abstract_regex
  14. {
  15. private:
  16. pcre2_code* pe;
  17. pcre2_match_data* pdata;
  18. public:
  19. pcre_regex()
  20. : pe(0)
  21. {
  22. pdata = pcre2_match_data_create(30, NULL);
  23. }
  24. ~pcre_regex()
  25. {
  26. if(pe)
  27. pcre2_code_free(pe);
  28. pcre2_match_data_free(pdata);
  29. }
  30. virtual bool set_expression(const char* pat, bool isperl)
  31. {
  32. if(!isperl)
  33. return false;
  34. if(pe)
  35. pcre2_code_free(pe);
  36. int errorcode = 0;
  37. PCRE2_SIZE erroroffset;
  38. pe = pcre2_compile((PCRE2_SPTR)pat, std::strlen(pat), PCRE2_MULTILINE, &errorcode, &erroroffset, NULL);
  39. return pe ? true : false;
  40. }
  41. virtual bool match_test(const char* text);
  42. virtual unsigned find_all(const char* text);
  43. virtual std::string name();
  44. struct initializer
  45. {
  46. initializer()
  47. {
  48. pcre_regex::register_instance(boost::shared_ptr<abstract_regex>(new pcre_regex));
  49. }
  50. void do_nothing()const {}
  51. };
  52. static const initializer init;
  53. };
  54. const pcre_regex::initializer pcre_regex::init;
  55. bool pcre_regex::match_test(const char * text)
  56. {
  57. int r = pcre2_match(pe, (PCRE2_SPTR)text, std::strlen(text), 0, PCRE2_ANCHORED, pdata, NULL);
  58. return r >= 0;
  59. }
  60. unsigned pcre_regex::find_all(const char * text)
  61. {
  62. unsigned count = 0;
  63. int flags = 0;
  64. const char* end = text + std::strlen(text);
  65. while(pcre2_match(pe, (PCRE2_SPTR)text, end - text, 0, flags, pdata, NULL) >= 0)
  66. {
  67. ++count;
  68. PCRE2_SIZE* v = pcre2_get_ovector_pointer(pdata);
  69. text += v[1];
  70. if(v[0] == v[1])
  71. ++text;
  72. if(*text)
  73. {
  74. flags = *(text - 1) == '\n' ? 0 : PCRE2_NOTBOL;
  75. }
  76. }
  77. return count;
  78. }
  79. std::string pcre_regex::name()
  80. {
  81. init.do_nothing();
  82. return std::string("PCRE-") + boost::lexical_cast<std::string>(PCRE2_MAJOR) + "." + boost::lexical_cast<std::string>(PCRE2_MINOR);
  83. }
  84. #endif