Programming Tips - C/C++: Wrapper class for PCRE

Date: 2015may31 OS: Linux Language: C/C++ Keywords: perl compatible regular expressions Q. C/C++: Wrapper class for PCRE A. Here's a simple C++ wrapper class There is also an official C++ wrapper by Google http://google.com?q=pcrecpp
--- mypcre.h --- #ifndef MY_PCRE_H #define MY_PCRE_H #include <string> #include <string.h> #include <stdlib.h> #include <stdio.h> // For snprintf() #include "pcre.h" class MyPcre { pcre *m_compiled; std::string m_line_to_match; int m_ovector_size; int *m_ovector; pcre_extra *m_extra = NULL; int m_nmatches; public: MyPcre(const int max_matches) { m_ovector_size = max_matches * 3; m_ovector = new int[m_ovector_size]; m_compiled = NULL; m_extra = NULL; m_nmatches = 0; } ~MyPcre() { if (m_ovector != NULL) { delete m_ovector; m_ovector = NULL; } if (m_compiled != NULL) { pcre_free(m_compiled); m_compiled = NULL; } if (m_extra != NULL) { pcre_free(m_extra); m_extra = NULL; } } bool compile(const char *expression) { const char *error = NULL; int erroff; m_compiled = pcre_compile(expression, 0, &error, &erroff, NULL); return m_compiled != NULL; } int exec(const char *line_to_match) { m_line_to_match = line_to_match; m_nmatches = pcre_exec(m_compiled, m_extra, line_to_match, strlen(line_to_match), 0, // Start looking at this point 0, // Options m_ovector, m_ovector_size)); return m_nmatches; } std::string get(const int i) { const char *psubStrMatchStr; pcre_get_substring(m_line_to_match.c_str(), m_ovector, m_nmatches, i, &(psubStrMatchStr)); std::string out = psubStrMatchStr; pcre_free_substring(psubStrMatchStr); return out; } void get(const int i, char *buf, const size_t bufsize) { const int start = m_ovector[2*i]; const int end = m_ovector[2*i+1]; snprintf(buf, bufsize, "%.*s", end - start, m_line_to_match.c_str() + start); } }; #endif
Example Use:
#include "mypcre.h" main() { MyPcre re; if (!re.compile("^([a-zA-Z]+):(.*)$")) { printf("Expression compile failed\n"); exit(1); } int nmatches = rc.exec("Subject: Hello"); if (nmatches <= 0) { printf("No matches\n"); exit(1); } for (int i = 0; i < nmatches; i++) { printf("%d = %s\n", i, re.get(i).c_str()); } }