C语言正则解析键值对异常:为何匹配结果不符合预期?
正则解析键值对失败的原因分析
void parseBuffer(char buffer[]) { regex_t regex; regmatch_t matches[3]; // Define the regular expression pattern char pattern[] = "([^:]+):[[:space:]]*([^\\r\\n]+)[\\r\\n]*"; // Compile the regular expression if (regcomp(®ex, pattern, REG_EXTENDED) != 0) { fprintf(stderr, "Failed to compile regex\n"); exit(EXIT_FAILURE); } // Loop through the buffer to find matches char *ptr = buffer; while (regexec(®ex, ptr, 3, matches, 0) == 0) { // Extract key and value using the matched positions char key[BUFF_SIZE], value[BUFF_SIZE]; strncpy(key, ptr + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so); strncpy(value, ptr + matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so); key[matches[1].rm_eo - matches[1].rm_so] = '\0'; value[matches[2].rm_eo - matches[2].rm_so] = '\0'; // Print or process the key-value pair printf("Key: %s, Value: %s\n", key, value); // Move the pointer to the next position after the match ptr += matches[0].rm_eo; } // Free the compiled regex regfree(®ex); }
我使用上述C语言函数
parseBuffer,通过正则表达式解析字符串中的key:value对。当输入字符串为Length: 10\r\nHello: hi\r\n\r\n"时,函数仅输出Key: Length, Value: 10\r\nHello: hi\r\n\r\n",无法正确解析出Length:10和Hello:hi两组键值对,请问该问题的原因是什么?
问题原因
核心问题出在正则表达式的匹配逻辑上,具体两点:
贪婪匹配导致值范围过度扩展
你正则里的[^\\r\\n]+是贪婪匹配规则,它会尽可能多地匹配非\r、\n的字符。如果你的输入字符串中,换行是用字面的\r\n字符序列(也就是\、r、\、n这四个可见字符)而非实际的\r、\n控制字符,这些字面字符并不在排除范围内,[^\\r\\n]+会直接把10后面的Hello: hi\r\n\r\n"全部纳入第一个值的匹配范围,导致后续没有内容可匹配。可选换行符的匹配逻辑漏洞
正则末尾的[\\r\\n]*是可选匹配(*表示0或多次),即使输入是实际的换行控制字符,某些情况下正则引擎可能优先让[^\\r\\n]+匹配更多内容,导致单次匹配覆盖多组键值对。
修复方案
修改正则表达式,明确每组键值对的终止边界:
// 强制要求每组键值对后至少有一个换行/回车符 char pattern[] = "([^:]+):[[:space:]]*([^\\r\\n]+)[\\r\\n]+";
如果需要兼容末尾无换行的键值对,可以调整为:
// 兼容末尾无换行的情况 char pattern[] = "([^:]+):[[:space:]]*([^\\r\\n]+)([\\r\\n]+|$)";
这样[^\\r\\n]+会在第一个换行符或字符串末尾停止匹配,确保每组键值对被单独识别。
内容的提问来源于stack exchange,提问作者johndaly69
相关产品推荐
相关产品推荐

