2

I'm trying to create a collection of regexes in C, with no much success.

Currently I'm trying to find include statements with the following regex:

(#include <.+>)|(#include \".+\")

here is my code:

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

char *regex_str = "(#include <.+>)|(#include \".+\")";
char *str = "#include <stdio.h>";

regex_t regex;
int reti;

int main() {
    /* Compile Regex */
    reti = regcomp(&regex, regex_str, 0);

    if (reti) {
        printf("Could not compile regex.\n");
        exit(1);
    }

    /* Exec Regex */
    reti = regexec(&regex, str, 0, NULL, 0);

    if (!reti) {
        printf("Match\n");
    } else if (reti == REG_NOMATCH) {
        printf("No Match\n");
    } else {
        regerror(reti, &regex, str, sizeof(str));
        printf("Regex match failed: %s\n", str);
        exit(1);
    }

    /* Free compiled regular expression if you want to use the regex_t again */
    regfree(&regex);

    return 0;
}

The result I get is: No Match

What am I doing wrong?

1

1 Answer 1

4

You might need to escape your match group:

char *regex_str = "\\(#include [\"<].*[\">]\\)";

Which could likely be rolled into one pattern.

Sign up to request clarification or add additional context in comments.

2 Comments

So which character I was supposed to escape?
The ( group ), which is defined by parentheses needs escaping eg. \\( ... \\)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.