正则表达式C - 缺少匹配?

时间:2016-06-24 15:21:38

标签: c regex

我在C中使用简单的正则表达式有问题,我的最后一场比赛无法识别。

这是我的代码:

NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context)
boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
String appPushEnabled = String.valueOf(areNotificationsEnabled);

使用以下条目字符串:#include <regex.h> int dummy(const char *s) { size_t nmatch = 0, i; regex_t preg; regmatch_t *pmatch = NULL; char str_regex[255 + 1]; /* Format : ID <ID> L {<Label>} R <Res> C {Info} T {More info} */ /* "C" and "T" aren't required */ snprintf(str_regex, 255, "ID ([[:alnum:]]{1,%d}) L \\{([^}]{1,%d})\\} R ([01])( C \\{[^}]+\\})?( T \\{[^}]+\\})?$", 25, // Max 25 chars for id 100); // Max 100 chars for label if (regcomp(&preg, str_regex, REG_EXTENDED) != 0) { fprintf(stderr, "Error initialization\n"); return 2; } // We got the number of matches nmatch = preg.re_nsub; pmatch = malloc (sizeof (*pmatch) * nmatch); // EDIT : problem solved with pmatch = malloc(size of(*pmatch) * (nmatch + 1)); if (pmatch == NULL) { fprintf(stderr, "Memory error\n"); return 4; } // String can't be found // EDIT : problem solved with : if (regexec(&preg, s, nmatch + 1, pmatch, 0) != 0) { if (regexec(&preg, s, nmatch, pmatch, 0) != 0) { regfree(&preg); free(pmatch); pmatch = NULL; fprintf(stderr, "String not valid\n"); return 5; } regfree (&preg); // EDIT : problem solved with : for (i = 0; i < nmatch + 1; ++i) { for (i = 0; i < nmatch; ++i) { char tmp[1000]; // Just for test, 1000 char not necessary int start = pmatch[i].rm_so; int finish = pmatch[i].rm_eo; memset(tmp, 0, sizeof(tmp)); strncpy(tmp, s + start, finish - start); printf("Match %d : <%s>\n", i, tmp); } }
我希望有5场比赛

  • 完整的链条,没关系
  • ID ID1 L {Label} R 1 C {Info1} T {Info2},没关系
  • <ID1>,没关系
  • <Label>,没关系
  • <1>,没关系
  • <C {Info1}>,它不起作用

知道为什么最后一场比赛不起作用? 如果我使用不带或带有最后一部分<T {Info2}>的链,它的作用相同。 “T”部分永远不会被识别......

编辑:用“nmatch + 1”代替nmatch解决问题,请参阅“编辑”部分上面的代码

2 个答案:

答案 0 :(得分:2)

根据man 3 regexre_nsub包含RE中的子表达式数。既然你也在捕获完整的字符串,那么你需要malloc(sizeof(*pmatch) * (nmatch + 1))吗?

答案 1 :(得分:0)

在nemetroid和man 3 regex的帮助下找到答案:你必须为nmatch + 1 match分配内存,然后将nmatch + 1代替nmatch传递给regexec() ,它确实有效。我的服务器上的Manpage并没有告诉我...... Grr。谢谢你的帮助!

相关问题