gpt4 book ai didi

c - C 中的 POSIX 正则表达式不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:30 25 4
gpt4 key购买 nike

我想匹配两个词 GET 和 HTTP 之间的所有内容。我尝试了我所知道的一切。但它不起作用。任何帮助表示赞赏。模式 GET.*HTTP 应匹配 GET www.google.com HTTP。

这是代码

标题:

#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

主要内容:

int main(int argc, char *argv[]) {
regex_t regex;
int reti;
char msgbuf[100];
regmatch_t pmatch[1];

/* Compile regular expression */
reti = regcomp(&regex, "GET.*HTTP", REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, argv[1], 1, pmatch, 0);

if (!reti) {
puts("Match");
char *match = strndup(argv[1] + pmatch[0].rm_so, pmatch[0].rm_eo - pmatch[0].rm_so);

printf("%s\n",match);
} else if (reti == REG_NOMATCH) {
puts("No match");
} else {
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}

/* Free compiled regular expression if you want to use the regex_t again */
regfree(&regex);

return 0;
}

我这里有什么地方做错了吗

最佳答案

看起来我的评论就是答案...

问题是命令行参数被分成 3 个字符串,使 argv[1] 仅指向 GET

要将整个字符串传递给程序,必须使用双引号:

$ ./regex GET www.google.com HTTP
No match
$ ./regex "GET www.google.com HTTP"
Match
GET www.google.com HTTP
$

关于c - C 中的 POSIX 正则表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7540600/

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