0

I have the following character pointer

char message[100] = "START_MESSAGE hello world \r\n\r\n";

I am trying to use regex.h to parse the above message. I want to get anything between START_MESSAGE and \r\n\r\n

So, I tried the following code (by following answer of THIS SO post)

#include <stdio.h>
#include <regex.h>
#include <stdlib.h>

int main() {
    regex_t regex;
    int reti;
    char msgbuf[100];

    reti = regcomp(&regex, "START_MESSAGE*\r\n\r\n", 0);
    reti = regexec(&regex, "START_MESSAGE hello world\r\n\r\n", 0, NULL, 0);

    if (!reti) {
        puts("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 memory allocated to the pattern buffer by regcomp() */
    regfree(&regex);

    return 0;
}

But, I get no match. I thought, maybe its because of the escape sequence. So, I put \\r\\n\\r\\n and still get no match. I looked for raw string literal (like r before the string in python). But, I get

error: stray ‘R’ in program

I tried removing \r\n\r\n and looked for only START_MESSAGE pattern, I get a match. How can I get \r\n\r\n to be matched or get the text between START_MESSAGE and \r\n\r\n.

chqrlie
  • 114,102
  • 10
  • 108
  • 170
InAFlash
  • 4,545
  • 7
  • 32
  • 53

0 Answers0