Cで単純な正規表現に問題があります。私の最後の試合は認識されません。ここで正規表現C - 不足している一致?
が私のコードです:
#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}
、それはOKだ、 <ID1>
OKです<Label>
、OKです<1>
は、それは、それは
最後のマッチが動作しない理由を任意のアイデアを動作しません
<C {Info1}>
、それは<T {Info2}>
OKですOKですか? 最後の部分があるかまたは最後の部分があるチェーンを使用する場合は、同じように動作します。(T {Info2})
「T」の部分は... EDITを認識されることはありません。代わりに、nmatchをの「nmatchを+ 1」で解決される問題は、man 3 regex
によると、「EDIT」の部分
私はre_nsubが完全な文字列自体を数えると思います。常にnmatchのサイズを見て、私はnmatch + 1:segfaultで試しました。 – RobinG