Regex.h: print a subexpression

I want to extract a substring from my expression using the regex.h library in C. Here is the code

#include <regex.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   regex_t    preg;   
   char       *string = "Random_ddName:cateof:Name_Random";

   char       *pattern = ".*Name:\\(.*\\):Name.*";
   int        rc;     
   size_t     nmatch = 1;
   regmatch_t pmatch[1];

   if (0 != (rc = regcomp(&preg, pattern, 0))) {
      printf("regcomp() failed, returning nonzero (%d)\n", rc);
      exit(EXIT_FAILURE);
   }

   if (0 != (rc = regexec(&preg, string, nmatch, pmatch, 0))) {
      printf("Failed to match '%s' with '%s',returning %d.\n",
      string, pattern, rc);
   }
   else {  
      printf("With the whole expression, "
             "a matched substring \"%.*s\" is found at position %d to %d.\n",
             pmatch[0].rm_eo - pmatch[0].rm_so, &string[pmatch[0].rm_so],
             pmatch[0].rm_so, pmatch[0].rm_eo - 1);
   }
   regfree(&preg);

    return 0;
}

I want to extract the string "cateof", but I want to make sure that between the strings is Name: and: Name. Cateof is random, it changes dynamically, and this is the only part I need. How can I get it right away? Can backlinks be used to store the value I need?

+3
source share
1 answer

You must specify , so that contains the full match and the breast file you want. nmatch = 2pmatch[0] pmatch[1]

Necessary code changes:

size_t     nmatch = 2;
regmatch_t pmatch[2];

and

...
    pmatch[1].rm_eo - pmatch[1].rm_so, &string[pmatch[1].rm_so],
    pmatch[1].rm_so, pmatch[1].rm_eo - 1);
...
+5
source

Source: https://habr.com/ru/post/1755568/


All Articles