利用第一和第二场比赛之间的职能regcomp和regexec切换在C语言中的正则表达式 [英] regex in C language using functions regcomp and regexec toggles between first and second match
问题描述
我使用的开发 - C ++ IDE编译我的C(WIN32 API)的方案。
I am using Dev-c++ IDE to compile my C (WIN32 API) programs.
我使用由 http://gnuwin32.sourceforge.net/packages/regex提供的正则表达式lirary热媒
我使用本文档,以供参考和同样已经从上述网站提供的...的 http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html
I am using this documentation for reference and the same has been provided from the above site... http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html
以下是code:
#include <cstdlib>
#include <iostream>
#include <sys/types.h>
#include <regex.h>
#include <conio.h>
#include <stdio.h>
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循环进入无限显示匹配的字符串的第一和第二末端位置,而不是进一步的打算。
The while loop goes infinite displaying the first and second end position of the matching string and not going further.
我已经使用了CNT变量来检查,持续6回合,然后我破坏循环停止运行无限
I have used the cnt variable to check for 6 turns and then i am breaking the loop to stop the infinite run.
输出是:
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);
}
您并没有实际上是通过你的字符串,这是什么原因造成了无休止的循环加强。
You were not actually stepping through your string, which was what caused the unending loop.
这篇关于利用第一和第二场比赛之间的职能regcomp和regexec切换在C语言中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!