【发布时间】:2015-05-15 14:36:03
【问题描述】:
所以我刚开始拿起 c 我的最终目标是编写一个函数,用正则表达式搜索字符串并返回匹配数组。
我遇到的最大问题是将字符串保存到内存中,这些字符串可以在作为参数传入的指针中返回或引用。
我真的很想知道有多少匹配项,这样我就可以做类似 c# 的事情; if(matches.Count() > 0) { /* we have a match! */ }
然后根据我最终传入的模式获取每个匹配组的结果字符串。
我知道这是不正确的,并且在实践中可能还有其他一些错误,但这是我试图找出它的代码,我试图通过阅读指针、结构、char 数组..etc 来解决这个问题
typedef struct
{
char *match;
} Matches;
int main()
{
regex_t regex;
int reti;
char msgbuf[100];
int max_matches = 10;
regmatch_t m[max_matches];
char str[] = "hello world";
reti = regcomp(®ex, "(hello) (world)", REG_EXTENDED);
if( reti )
{
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(®ex, str, (size_t) max_matches, m, 0);
if( !reti )
{
puts("Match");
}
else if( reti == REG_NOMATCH )
{
puts("No match");
}
else
{
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
char *p = str;
int num_of_matches = 0;
Matches *matches;
int i = 0;
for(i = 0; i < max_matches; i++)
{
if (m[i].rm_so == -1) break;
int start = m[i].rm_so + (p - str);
int finish = m[i].rm_eo + (p - str);
if (i == 0)
printf ("$& is ");
else
printf ("$%d is ", i);
char match[finish - start + 1];
memcpy(match, str + start, finish - start);
match[sizeof(match)] = 0;
matches[i].match = match; //Need to get access to this string in an array outside of the loop
printf ("'%.*s' (bytes %d:%d)\n", (finish - start), str + start, start, finish);
num_of_matches++;
}
p += m[0].rm_eo;
for(i = 0; i < num_of_matches; i++)
{
printf("'%s'\n", matches[i].match);
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(®ex);
return 0;
}
当我认为我只匹配“世界”时我注意到当我注释掉 printf 语句时,最后一个 printf 语句返回空字符或随机字符。
【问题讨论】:
标签: c