Search code examples
chttp-headersglib

Regexp to match http header format with "g_regex_match_simple"


I'm trying to match HTTP header format in C using glib's g_regex_match_simple:

static const char header_regex[] = "/([\\w-]+): (\\w+)";

...

const char header[] = "Test: header1";
if (g_regex_match_simple(header_regex, header, 0, 0))
{
    headers[index] = g_strdup(header);
    index++;
}
else
{
    error_setg(errp, "%s is not a valid http header format", header);
    goto cleanup;
}

I'm getting FALSE out of g_regex_match_simple() even though "Test: header1" should be valid.

What am I missing?

I tried the answer in Regexp to match logcat brief format with g_regex_match_simple but it didn't work for me.

Ideas?


Solution

  • The following are compiled with clang -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include youe_file.c -lgobject-2.0 -lglib-2.0.

    #include <stdio.h>
    #include <glib.h>
    
    static const char header_regex[] = "([\\w-]+): (\\w+)";
    
    
    int main()
    {
    const char header[] = "Test: header1";
    if (g_regex_match_simple(header_regex, header, 0, 0)){
     printf("+\n");}
    else {
        printf("-\n");
    }
    
    return 0;
    }
    

    And it gives a positive match. The difference were in regexp pattern. I've removed a slash.

    Original string static const char header_regex[] = "/([\\w-]+): (\\w+)"; needs to be static const char header_regex[] = "([\\w-]+): (\\w+)";

                                       ^
                                       |
                                    no slash here