Search code examples
cregexposixposix-ere

POSIX regular expression with extended syntax not matching where it should


I am trying to use POSIX regex in C, but it's not working. Here's my code:

int regi(char *c, char *e)
{
    regex_t regex;
    int reti = regcomp(&regex, e, 0);
    reti = regexec(&regex, c, 0, NULL, 0);

    if(!reti)
        return 1;

    return 0;
}

int main()
{
   char str[5] = {'0','x','2','F'};

   if(regi(str, "^(0[xX])[0-9a-fA-F]+"))
      // Do stuff

   return 0;
}

I was looking here: http://www.peope.net/old/regex.html

This never goes inside the if statement.


Solution

  • In order to use the + metacharacter, you need to tell regcomp() that you're using the extended POSIX syntax:

    int reti = regcomp(&regex, e, REG_EXTENDED);
    

    There are several other problems with this code, though, including casting const char* to char*, and ignoring the return value of regcomp().