2

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.

fuz
  • 88,405
  • 25
  • 200
  • 352
neby
  • 103
  • 1
  • 2
  • 9

2 Answers2

5

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().

一二三
  • 21,059
  • 11
  • 65
  • 74
3

I've never quite gotten to grips with the different flavours of regexes, but I seems that basic regexes don't know the qualifier +, only *.

One solution is to use extended regexes. You have to specify that when you compose the regex:

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

(I thought that + could be emulated with "\\{1,\\}" in basic regexes, but that didn't work.)

M Oehm
  • 28,726
  • 3
  • 31
  • 42