gpt4 book ai didi

C编程-正则表达式匹配和存储在字符串中

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:58 24 4
gpt4 key购买 nike

我可以使用 C 中的正则表达式库匹配模式。可以打印匹配的单词。但是,我需要将匹配项存储到字符串或字符数组中。代码如下:

void match(regex_t *pexp, char *sz) {
regmatch_t matches[MAX_MATCHES]; //A list of the matches in the string (a list of 1)
if (regexec(pexp, sz, MAX_MATCHES, matches, 0) == 0)
{
printf("%.*s\n", (int)(matches[0].rm_eo - matches[0].rm_so), sz + matches[0].rm_so);
}
else {
printf("\"%s\" does not match\n", sz);
}
}

int main() {
int rv;
regex_t exp;
rv = regcomp(&exp, "-?([A-Z]+)", REG_EXTENDED);
if (rv != 0) {
printf("regcomp failed with %d\n", rv);
}
match(&exp, "456-CCIMI");
regfree(&exp);
return 0;
}

或者可能只是我需要这个。我如何在 C 中拼接 char 数组? IE。如果 char 数组有“ABCDEF”6 个字符。我只需要索引 2 中的字符来索引 5“CDEF”。

最佳答案

对于你提供的例子,如果你想要-CCIMI,你可以

strncpy(dest, sz + matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so);

但是由于您在模式中使用了组,我猜您真正想要的只是 CCIMI。你可以

strncpy(dest, sz + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);

strncpy()之前,请为dest做malloc足够的空间

关于C编程-正则表达式匹配和存储在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com