Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
匹配C中的POSIX子字符串_C_Regex_Pattern Matching_Posix - Fatal编程技术网

匹配C中的POSIX子字符串

匹配C中的POSIX子字符串,c,regex,pattern-matching,posix,C,Regex,Pattern Matching,Posix,我想打印match“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, c

我想打印match“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%)";'
发生在FGET之后

我收到的打印行是来自另一个函数的未格式化printf语句,该函数在该函数之后运行。关于我的问题可能在哪里,我有一些不同的想法(regex语法、内存分配、regmatch__t的使用),整个上午我都在尝试不同的解决方案组合,但到目前为止都没有效果


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

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

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);

您以前可能没有见过的格式字符串,但这很好地涵盖了它。

您只需要删除反斜杠,而不是用星号替换第二个。如现在所写,它将匹配
字节
字节
。(嗯,看起来OP试图编写一个基本的正则表达式,暂时忘记了C的字符串转义,但还是编译成了扩展的RE。)@pilcrow这是一个愚蠢的错误,谢谢你指出。