Home > Software design >  C regex not matched
C regex not matched

Time:05-02

I'm trying to match this regex ^%-?\ ?#?0?$ with regexec, it works fine on this site, but something might be wrong because regexec doesn't work :

#include <regex.h>
#include <stdio.h>

int main(void) {
    regex_t regex;
    if (regcomp(&regex, "^%-?\\ ?#?0?$", 0) != 0) {
        return -1;
    }
    const int match = regexec(&regex, "%-", 0, NULL, REG_EXTENDED);
    if (match == 0) {
        puts("Matched !");
    }
    else {
        puts("Not found !");
    }
    return 0;
}

This example shall display "Matched", but it says "Not found". Does the problem come from my regex ?

CodePudding user response:

The REG_EXTENDED flag should be set when compiling the regex with regcomp, not on matching it with regexec. If you do that, it works, so:

if (regcomp(&regex, "^%-?\\ ?#?0?$", REG_EXTENDED) != 0) {
    return -1;
}

const int match = regexec(&regex, "%-", 0, NULL, 0);

(I don't know whether POSIX mandates concrete values for the flags, but in my implementation, the compilation flag REG_EXTENDED has the same value as the matching flag REG_NOTBOL, which always fails to match the beginning of the string with ^.)

CodePudding user response:

If some will read this page later, the final code is :

int main(void) {
    regex_t regex;
    if (regcomp(&regex, "^%-?\\ ?#?0?$", REG_EXTENDED) != 0) {
        return -1;
    }
    const int match = regexec(&regex, "%-", 0, NULL, 0);
    if (match == 0) {
        puts("Matched !");
    }
    else {
        puts("Not found !");
    }
    return 0;
}

I added the REG_EXTENDED flag when compiling regex, but removed it when executed.

  • Related