首页 > 解决方案 > 正则表达式将 http 标头格式与“g_regex_match_simple”匹配

问题描述

我正在尝试使用 glib 匹配 C 中的 HTTP 标头格式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;
}

g_regex_match_simple()即使“测试:header1”应该是有效的,我也得到了 FALSE 。

我错过了什么?

我尝试了 Regexp 中的答案以将 logcat 简短格式与 g_regex_match_simple 匹配, 但它对我不起作用。

想法?

标签: chttp-headersglib

解决方案


以下是用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;
}

它给出了一个积极的匹配。不同之处在于regexp模式。我删除了一个斜线。

原始字符串static const char header_regex[] = "/([\\w-]+): (\\w+)"; 需要是static const char header_regex[] = "([\\w-]+): (\\w+)";

                                   ^
                                   |
                                no slash here

推荐阅读