Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why regex always returns 1?

Tags:

c

regex

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
}
like image 362
abcxyz Avatar asked Apr 23 '15 14:04

abcxyz


1 Answers

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.

like image 61
unwind Avatar answered Oct 19 '22 21:10

unwind