C正则表达式 - 获取匹配的字符串

时间:2014-02-21 17:43:45

标签: c regex

我有这段代码:

regex_t regex;
    int reti;

    reti = regcomp(&regex, "[0-9]", REG_EXTENDED);

    reti = regexec(&regex, "sdsda5dada", 0, NULL, 0);
    if( !reti ){
        return 1;
    }
    else if( reti == REG_NOMATCH ){
        return 0;
    }

    regfree(&regex);

匹配字符串sdsda5dada中包含的 5 数字。如何进入匹配部分的变量?假设我有一个名为char *的{​​{1}}变量,如何将 5 放入该变量?

我知道这是一个非常棒的问题,但我对正则表达不太了解。提前谢谢。

1 个答案:

答案 0 :(得分:0)

man regexec州:

The 0th member of the pmatch array is filled in to indicate what substring
of string was matched by the entire RE. Remaining members report what
substring was matched by parenthesized subexpressions within the RE.

因此,您必须将pmatch参数指向至少一个元素的regmatch_t数组,并将nmatch设置为pmatch的大小。 rm_so的{​​{1}}和rm_se字段将指出字符串的匹配部分:

pmatch[0]

它不是NUL终止,如果你想要一个合适的C字符串,你将不得不复制它,例如:

 const char *string = "sdsda5dada";
 const char *digit_start = string + pmatch[0].rm_so;
 const char *digit_end = string + pmatch[0].rm_se;
 int digit_len = digit_end - digit_start;

char digit_copy[10]; if (digit_len >= sizeof(digit_copy)) digit_len = sizoef(digit_copy) - 1; memcpy(digit_copy, digit_start, digit_len); digit_copy[digit_len] = '\0'; 是第三个参数,nmatch是第四个参数。这是简介:

patch