0

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".

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Be aware that strncpy may not add the string terminator.
1

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.

2 Comments

i am getting this warning while compiling "incompatible implicit declaration of built-in function ‘malloc’"
@user2943851 Any decent reference for malloc will tell you what header file you need to include.
0

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);

1 Comment

Be aware that strncpy may not add the string terminator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.