Michael Bellissimo
Michael Bellissimo

Reputation: 11

regex incorrect c

Hey so I'm trying to get this regex to work and when I type in "Hello" as the sentences input and "H" afterwards as the rgx, what I thought was just a basic regex match is outputting that it's not there each time I try anything similar. It only matches randomly correctly.

typedef char String[128];

int main(void) {

    String rgx;
    regex_t CompiledRegExp;

    String sentences;
    fgets(sentences, 128, stdin);

    fgets(rgx, 128, stdin);
    if (regcomp(&CompiledRegExp,rgx,0) != 0) {
        printf("ERROR: Something wrong in the regular expression\n");
        exit(EXIT_FAILURE);
    }

    if (regexec(&CompiledRegExp,sentences,0,NULL,0) == 0) {
        printf("Yes, it's there\n");
    } else {
        printf("No, it's not there\n");
    }

    regfree(&CompiledRegExp);

    return(EXIT_SUCCESS);
}

Upvotes: 0

Views: 47

Answers (1)

rici
rici

Reputation: 241701

From man fgets (emphasis added):

The fgets() function shall read bytes from stream into the array pointed to by s, until n−1 bytes are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.

A newline character in a regex is treated like any other ordinary character: it only matches itself. So if your regex is H followed by a newline, it will only match a string in which an H is followed by a newline. In your example input, the H is followed by an e.

Upvotes: 3

Related Questions