【问题标题】:Regexp to match http header format with "g_regex_match_simple"正则表达式将 http 标头格式与“g_regex_match_simple”匹配
【发布时间】:2020-02-16 11:01:00
【问题描述】:

我正在尝试使用 glib 的 g_regex_match_simple 匹配 C 中的 HTTP 标头格式:

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() 中得到了 FALSE,即使“Test: header1”应该是有效的。

我错过了什么?

我尝试了答案 Regexp to match logcat brief format with g_regex_match_simple 但它对我不起作用。

想法?

【问题讨论】:

  • 您的模式中有slash 字符,而测试字符串中没有slash 字符。
  • 谢谢!你说得对!我用第一个 slash 复制了正则表达式字符串,而不是省略它...
  • 如果问题确实解决了您的特定问题,您可能应该将问题标记为已接受。

标签: c http-headers glib


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多