Regular expressions in C: examples?

后端 未结 5 1141
傲寒
傲寒 2020-11-22 04:57

I\'m after some simple examples and best practices of how to use regular expressions in ANSI C. man regex.h does not provide that much help.

5条回答
  •  遇见更好的自我
    2020-11-22 05:28

    This is an example of using REG_EXTENDED. This regular expression

    "^(-)?([0-9]+)((,|.)([0-9]+))?\n$"
    

    Allows you to catch decimal numbers in Spanish system and international. :)

    #include 
    #include 
    #include 
    regex_t regex;
    int reti;
    char msgbuf[100];
    
    int main(int argc, char const *argv[])
    {
        while(1){
            fgets( msgbuf, 100, stdin );
            reti = regcomp(®ex, "^(-)?([0-9]+)((,|.)([0-9]+))?\n$", REG_EXTENDED);
            if (reti) {
                fprintf(stderr, "Could not compile regex\n");
                exit(1);
            }
    
            /* Execute regular expression */
            printf("%s\n", msgbuf);
            reti = regexec(®ex, msgbuf, 0, NULL, 0);
            if (!reti) {
                puts("Match");
            }
            else if (reti == REG_NOMATCH) {
                puts("No match");
            }
            else {
                regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
                fprintf(stderr, "Regex match failed: %s\n", msgbuf);
                exit(1);
            }
    
            /* Free memory allocated to the pattern buffer by regcomp() */
            regfree(®ex);
        }
    
    }
    

提交回复
热议问题