Regular expressions in C: examples?

后端 未结 5 1091
傲寒
傲寒 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:14

    Regular expressions actually aren't part of ANSI C. It sounds like you might be talking about the POSIX regular expression library, which comes with most (all?) *nixes. Here's an example of using POSIX regexes in C (based on this):

    #include         
    regex_t regex;
    int reti;
    char msgbuf[100];
    
    /* Compile regular expression */
    reti = regcomp(®ex, "^a[[:alnum:]]", 0);
    if (reti) {
        fprintf(stderr, "Could not compile regex\n");
        exit(1);
    }
    
    /* Execute regular expression */
    reti = regexec(®ex, "abc", 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);
    

    Alternatively, you may want to check out PCRE, a library for Perl-compatible regular expressions in C. The Perl syntax is pretty much that same syntax used in Java, Python, and a number of other languages. The POSIX syntax is the syntax used by grep, sed, vi, etc.

提交回复
热议问题