查找匹配

正则表达式

#include <regex.h>

const char *data = "Pi is equal to 3.14";
//POSIX regex has no \d: the class [0-9] instead
const char *pattern = "[0-9]+\\.[0-9]+";

//REG_EXTENDED: + ? | ( ) work without a backslash
regex_t regex;
if (regcomp(&regex, pattern, REG_EXTENDED) != 0) {
    exit(EXIT_FAILURE);
}

//rm_so and rm_eo are the start and the end of the match
regmatch_t match[1];
if (regexec(&regex, data, 1, match, 0) == 0) {
    int start = match[0].rm_so;
    //start is 15
    double pi = strtod(data + start, nullptr);
    //pi is 3.14

    printf("start is %d\n", start);
    printf("pi is %g\n", pi);
}
regfree(&regex);