简体   繁体   中英

Why regex always returns 1?

The following function checks if a variable name start with a letter and may have preceding characters which are letters/ numbers. Why does the return value is always 1 no matter what the input is?

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

int validate_var(char *str)
{
    regex_t reg;
    regcomp(&reg, "^[a-zA-Z]+[a-zA-Z0-9]*$", 0);
    int r = regexec(&reg, str, 0, NULL, 0);
    regfree(&reg);

    return r;
}

int main() {
    printf("%d\n", validate_var("abc")); // Reports 1, This makes sense
    printf("%d\n", validate_var("17"));  // Reports 1, This doesn't make sense
}

You're using anchors ( ^ and $ ) but not enabling extended syntax by passing REG_EXTENDED to regcomp() . See the manual page .

You should really check all return values, there should be a failure reported somewhere due to the syntax usage error.

Note that non-zero means failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM