使用函数regcomp和regexec在C语言中的正则表达式在第一次和第二次匹配之间切换

我正在使用Dev-c ++ IDE来编译我的C(WIN32 API)程序。

我正在使用http://gnuwin32.sourceforge.net/packages/regex.htm提供的正则表达式

我使用此文档作为参考,上述网站提供了相同的内容… http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html

以下是守则:

#include  #include  #include  #include  #include  #include  using namespace std; int main(int argc, char *argv[]) { int a; regex_t re; char str[128] = "onces sam lived with samle to win samile hehe sam hoho sam\0"; regmatch_t pm; a = regcomp(&re,"sam", 0); if(a!=0) { puts("Invalid Regex"); getch(); return 0; } a = regexec(&re, &str[0], 1, &pm, REG_EXTENDED); printf("\n first match at %d",pm.rm_eo); int cnt = 0; while(a==0) { a = regexec(&re, &str[0] + pm.rm_eo, 1, &pm, 0); printf("\n next match %d",pm.rm_eo); cnt++; if(cnt>6)break; } getch(); return EXIT_SUCCESS; } 

while循环无限显示匹配字符串的第一个和第二个结束位置,而不是更进一步。

我已经使用cnt变量检查了6个回合然后我打破循环以停止无限运行。

输出是:

第一场比赛是9

下一场比赛15

下一场比赛9

下一场比赛15

下一场比赛9

下一场比赛15

我在这里缺少什么?

试试这个:

 int cnt = 0; int offset = 0; a = regexec(&re, &str[0], 1, &pm, REG_EXTENDED); while(a==0) { printf("\n %s match at %d", offset ? "next" : "first", offset+pm.rm_so); offset += pm.rm_eo; cnt++; a = regexec(&re, &str[0] + offset, 1, &pm, 0); } 

你实际上并没有单步执行你的字符串,这是造成无休止循环的原因。