Reputation: 269
I am able to match patterns using regex library in C. The matched words can be printed. But, i need to store the matches into a string or char array. The code is below:
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;
}
OR may be just i need this. How can i splice char array in C? ie. if a char array has "ABCDEF" 6 characters. I just need the chars in index 2 to index 5 "CDEF".
Upvotes: 0
Views: 1122
Reputation: 31
For the example you provided, if you want -CCIMI
, you can
strncpy(dest, sz + matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so);
But since you used group in pattern, I guess what you really want is just CCIMI
. You can
strncpy(dest, sz + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
Before strncpy()
, please do malloc sufficient space for dest
Upvotes: 3
Reputation: 379
you can use strncpy also, if you are looking for a string function.
strncpy(dest, sz + matches[0].rm_so, matches[0].rm_eo - matches[0].rm_so);
Upvotes: 0
Reputation: 409442
You can use memcpy
to copy the matched string to an array, or dynamically allocate a string:
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 */
After the above code, dest
points to the matched string.
Upvotes: 1