[英]C programming- Regex matching and store in string
我可以使用C中的regex庫來匹配模式。可以打印匹配的單詞。 但是,我需要將匹配項存儲到字符串或char數組中。 代碼如下:
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數組? 即。 如果char數組具有“ ABCDEF” 6個字符。 我只需要索引2中的char來索引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
分配足夠的空間
您可以使用memcpy
將匹配的字符串復制到數組,或動態分配字符串:
char *dest;
/* your regexec call */
dest = malloc(matches[0].rm_eo - matches[0].rm_so + 1); /* +1 for terminator */
memcpy(dest, sz + matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so);
dest[matches[0].rm_eo - matches[0].rm_so] = '\0'; /* terminate the string */
在上面的代碼之后, dest
指向匹配的字符串。
如果要查找字符串函數,也可以使用strncpy。
strncpy(dest, sz + matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.