1

Dev-c ++ IDEを使用してC(WIN32 API)プログラムをコンパイルしています。

http://gnuwin32.sourceforge.net/packages/regex.htmによって提供される正規表現のliraryを使用しています

私はこのドキュメントを参照用に使用しており、同じものが上記のサイトから提供されています... http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html

以下はコードです:

#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ループは無限になり、一致する文字列の最初と2番目の終了位置を表示し、それ以上進みません。

cnt変数を使用して6ターンをチェックし、ループを中断して無限の実行を停止しています。

出力は次のとおりです。

9時の最初の試合

次の試合15

次の試合9

次の試合15

次の試合9

次の試合15

ここで何が欠けていますか?

4

2 に答える 2

1

代わりにこれを試してください:

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);
}

あなたは実際にあなたの文字列をステップスルーしていませんでした、それが終わりのないループを引き起こしたものでした。

于 2012-07-07T18:52:46.910 に答える
0

私はこのコードを思いつき、@ jxhソリューションを少し改善(よりコンパクト)し、余分なルックアップの使用を回避します&str[0]

int cnt = 0;
int offset = 0;
while(!regexec(&re, str + offset, 1, &pm, REG_EXTENDED)) {
    printf("%s match at %d\n", offset ? "next" : "first", offset+pm.rm_so);
    offset += pm.rm_eo;
    cnt++;
}
于 2021-12-19T01:16:02.570 に答える