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);
}
For this input: Length: 10\r\nHello: hi\r\n\r\n", why does parsebuffer print the key as Length and the value as the rest of the string? I want to print 2 different keys and 2 different values (Length: 10 and Hello: hi).
In
\\rand\\nare not CR and LF, but two escaped\characters, and the literalrandncharacters.In other words,
"\\r\\n"is a string containing the ASCII bytes5C 72 5C 6E.You want to use the actual
'\r'and'\n'characters (ASCII0Dand0A).A slightly refactored example: