regex.h:打印子表达式

时间:2010-07-20 17:02:52

标签: c regex

我想使用C中的regex.h库从表达式中提取子字符串。这是代码

#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;
}

我想提取字符串“cateof”,但我想确保它们在字符串之间 姓名:和:姓名。 cateof是随机的,它会动态变化,这是我需要的唯一部分。我怎样才能立刻得到它?是否可以使用反向引用来存储我需要的值?

1 个答案:

答案 0 :(得分:5)

您必须指定 nmatch = 2 ,以便pmatch[0]包含整个匹配项, pmatch[1] 包含您想要的子匹配项。

需要更改代码:

size_t     nmatch = 2;
regmatch_t pmatch[2];

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