gpt4 book ai didi

c - C中http header 的正则表达式

转载 作者:可可西里 更新时间:2023-11-01 17:06:34 29 4
gpt4 key购买 nike

我想从 http header 中提取字符串,例如:GET http://www.example.com HTTP/1.1 使用正则表达式。我使用这种模式:^([A-Za-z]+)(\s+)(http?):\/\/(.*)(\s+)(HTTP\/)([0-9 ].[0-9]) 这很好用并拆分了 GEThttp://www.example.comHTTP/1.1 。但是当我在 C 中使用此模式时,它不会转义 /(即 \/\/ 在 C 中未检测到)。我怎样才能做到这一点?或者是否有更好的模式从 http header 中提取字符串?

最佳答案

请注意,您不需要转义 C 正则表达式库中的正斜杠,因为 regcomp 不支持正则表达式分隔符。

您只需正确初始化regmatch_tsize_t 变量,使用\s 速记字符类的双重转义,然后通过正则表达式编译器的 REG_EXTENDED 标志。

我还建议将模式减少到只有 3 个捕获组:

const char *str_regex = "([A-Za-z]+) +(http?://.*) +(HTTP/[0-9][.][0-9])";

请注意,通过将点放入括号表达式中,点被“转义”了。

完整 C demo提取 GEThttp://www.example.comHTTP/1.1:

#include <stdio.h>
#include <stdlib.h>
#include <regex.h>

int main (void)
{
int match;
int err;
regex_t preg;
regmatch_t pmatch[4]; // We have 3 capturing groups + the whole match group
size_t nmatch = 4; // Same as above
const char *str_request = "GET http://www.example.com HTTP/1.1";

const char *str_regex = "([A-Za-z]+) +(http?://.*) +(HTTP/[0-9][.][0-9])";
err = regcomp(&preg, str_regex, REG_EXTENDED);
if (err == 0)
{
match = regexec(&preg, str_request, nmatch, pmatch, 0);
nmatch = preg.re_nsub;
regfree(&preg);
if (match == 0)
{
printf("\"%.*s\"\n", pmatch[1].rm_eo - pmatch[1].rm_so, &str_request[pmatch[1].rm_so]);
printf("\"%.*s\"\n", pmatch[2].rm_eo - pmatch[2].rm_so, &str_request[pmatch[2].rm_so]);
printf("\"%.*s\"\n", pmatch[3].rm_eo - pmatch[3].rm_so, &str_request[pmatch[3].rm_so]);
}
else if (match == REG_NOMATCH)
{
printf("unmatch\n");
}
}
return 0;
}

关于c - C中http header 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38707333/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com