gpt4 book ai didi

c - 在 C 中匹配 POSIX 子串

转载 作者:太空宇宙 更新时间:2023-11-04 04:48:52 24 4
gpt4 key购买 nike

我想打印匹配“bytes”的子表达式。我已简化此示例,以便我可以调试代码的其他组件:

char *bytes="[[:print:]]*\(bytes\)";
regex_t compiled;
regmatch_t matches[2];
char currentLine[512];

fgets(currentLine, 512, ifile);
regcomp(&compiled, bytes, REG_EXTENDED);
if(regexec(&compiled, currentLine, 2, matches, 0)==0){
printf("%s\n", bytes+matches[1].rm_so);
}

在哪里

currentLine= "Free Memory: 5062026704 bytes (79%)";'

发生在 fgets 之后。

我收到的打印行是来自另一个函数的未格式化的 printf 语句 - 一个在这个函数之后运行的函数。对于我的问题可能出在哪里(正则表达式语法、内存分配、regmatch_t 的使用),我有一些不同的想法,而且我整个上午都在尝试不同的解决方案组合,但到目前为止都无济于事。

如何正确打印匹配的子串?

最佳答案

不同的问题,但使用了 here 中的一些示例代码我修改了这一行:

char *bytes="[[:print:]]*\(bytes\)";
^ ^

为此:

char *bytes="[[:print:]]*(bytes)";
^

并修改打印语句如下:

printf("0: [%.*s]\n", matches[0].rm_eo - matches[0].rm_so, currentLine + matches[0].rm_so);
printf("1: [%.*s]\n", matches[1].rm_eo - matches[1].rm_so, currentLine + matches[1].rm_so);

你以前可能没有见过的格式字符串,但是这个 thread覆盖得很好。

关于c - 在 C 中匹配 POSIX 子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18063370/

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