Can I use regex_t for several compilations

advertisements

Basic question, not clear to me for the regcomp man.

If I have a static instance of regex_t, can I reuse it for several compilation without freeing it every time, something like:

    int match(char* pattern, char* name) {
       static regex_t re;
       regcomp(&re,pattern,REG_EXTENDED|REG_NOSUB);
      ...
    }

The code itself is bit more complicated, and the idea is to use static variable to save compilation if the pattern was not changed between calls. The question is if I need to call regfree before each new regcomp.

Thanks.


If you want to use the previous result of regcomp() that was compiled into re that's perfectly fine - as long as you don't call regfree() in the meantime.

But when you want to compile a new regex by calling regcomp() again, you'll need to call regfree() to properly release any resources used by the previous regcomp() call. So you'll probably need some other static variable that keeps track of whether or not the re variable has been used by a call to regcomp() and needs to be regfree()-ed before being reused.

Something along the lines of:

int match(char* pattern, char* name) {
   static regex_t re;
   static int re_in_use = 0;

   if (isNewRegex( pattern)) {  // however you want to determine this...
        if (re_in_use) {
            regfree( &re);
            re_in_use = 0;
        }
   }

   re_in_use = regcomp(&re,pattern,REG_EXTENDED|REG_NOSUB);

  ...
}