fork download
  1. #include <regex.h>
  2. #include <stdio.h>
  3.  
  4. int main( int argv, char* args[] )
  5. {
  6. char checkString[] = "abc, def, ghi"; // チェックをする文字列
  7. const char regex[] = "([a-z]+), ([a-z]+), ([a-z]+)"; // マッチングをする文字列
  8. regex_t regexBuffer; // 正規表現オブジェクト
  9. int i,j;
  10. int size;
  11. // パターンにマッチングしたインデックス格納する構造体
  12. regmatch_t patternMatch[4];
  13.  
  14. // 正規表現オブジェクトのコンパイル
  15. if( regcomp( &regexBuffer, regex, REG_EXTENDED | REG_NEWLINE ) != 0 )
  16. {
  17. puts("regex compile failed" );
  18. return 1;
  19. }
  20.  
  21. size = sizeof( patternMatch ) / sizeof( regmatch_t );
  22. if( regexec( &regexBuffer, checkString, size, patternMatch, 0 ) != 0 )
  23. {
  24. puts("No match!!");
  25. return 1;
  26. }
  27.  
  28. // マッチした場合patternMatch構造体に文字列のindex番号が入る
  29. // 配列の数がマッチ数を超えていた場合超えた構造体の各要素には-1が入る
  30. for( i = 0; i < size; ++i )
  31. {
  32. int startIndex = patternMatch[i].rm_so;
  33. int endIndex = patternMatch[i].rm_eo;
  34. if( startIndex == -1 || endIndex == -1 )
  35. {
  36. puts("exit");
  37. continue;
  38. }
  39. for(j=startIndex;j<endIndex;j++)putchar(checkString[j]);
  40. putchar('\n');
  41. }
  42.  
  43. // オブジェクトの開放
  44. regfree( &regexBuffer );
  45. return 0;
  46. }
Success #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
abc, def, ghi
abc
def
ghi