'regcomp() failed with 'Success'

I'm trying to use a regex in order to validate a file-name. Tried this string

"^(?!(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.[^.]*)?$)[^<>:\"/\\\|\\?*\x00-\x1F]*[^<>:\"/\\\|\?*\x00-\x1F\\ .]$"

in online checker : https://www.freeformatter.com/regex-tester.html Works as expected for 'video-'
-> Fully matches the source string!.

However, using:

    bool regexCompile(regex_t &regex, const char *pattern)
    { 
        int res = 0;
        res = regcomp(&regex, pattern, REG_EXTENDED);
        printf("res = %d\n",res);
        if(res) // regex compiled unsuccessfully
        {
            int     rc;
            char    buffer[100];
            regerror(rc, &regex, buffer, 100);
            printf("regcomp() failed with '%s'\n", buffer);
            return false;
        }
        return true;
     }

bool isValidFileName(const char *fileName)
{
    regex_t regex;
    int res = 0;
    // regex not complete
    const char* pattern = "^(?!(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\\.[^.]*)?$)[^<>:\"/\\\\|?*\x00-\x1F]*[^<>:\"/\\\\|\\?*\x00-\x1F\\ .]$";
    if(regexCompile(regex, pattern) != true)
    {
        return false;
    }
    res = regexec(&regex, fileName, 0, NULL, 0);
    if(!res)
    {
        return true;
    }
    return false;
}

I get for the filename "video-":

res = 13
regcomp() failed with 'Success'
0

any extra backslash need to be added in the c-regex version? Thanks.



Solution 1:[1]

In the line

regerror(rc, &regex, buffer, 100);

You pass the indeterminate value of the uninitialized variable rc. You should be passing the error you got back from regcomp, i.e. res:

regerror(res, &regex, buffer, sizeof(buffer));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1