Search code examples
cregexalphanumeric

Check if a string is all alphanumeric with regular expressions in C programming


I want to check whether a string only contains alphanumeric characters or not in C. I do not want to use the isalnum function. Why doesn't the code below work correctly?

int main()
{
    printf("test regular expression\n");
    int retval = 0;
    regex_t re;
    char line[8] = "4a.zCCb";
    char msgbuf[100];
    if (regcomp(&re,"[a-zA-z0-9]{2,8}", REG_EXTENDED) != 0)
    {
        fprintf(stderr, "Failed to compile regex '%s'\n", tofind);
        return EXIT_FAILURE;
    }
    if ((retval = regexec(&re, line, 0, NULL, 0)) == 0)
        printf("Match : %s\n", line);
    else  if (retval == REG_NOMATCH)
        printf("does not match : %s\n", line);
    else {
        regerror(retval, &re, msgbuf, sizeof(msgbuf));
        fprintf(stderr, "Regex match failed: %s\n", msgbuf);
        exit(1);
    }
    regfree(&re);
}

Solution

  • If you want the entire string to be alphanumeric, you need to include begin and end anchors in the regex:

    "^[a-zA-Z0-9]{2,8}$"
    

    As it stands, there are 4 alphanumerics at the end of the string, which matches the original regex.