kpcre1.c
最終更新:2009/12/30
001: /* kpcre.c 002: * 正規表現を用いたマッチの例 (PCRE 使用) 003: */ 004: 005: #define USAGE "Usage kpcre <string> <pattern>\n" 006: 007: #define OVECSIZE 99 008: 009: #include "mystab.h" 010: #include "apr_strings.h" 011: 012: #include "pcre.h" 013: 014: int apr_my_main ( 015: int ac, char **av 016: , apr_file_t * astdin 017: , apr_file_t * astdout 018: , apr_file_t * astderr 019: , apr_pool_t * pool 020: ) { 021: 022: int error_flag = 0; 023: 024: if (ac < 3) { 025: apr_file_printf(astderr, USAGE); 026: goto _FINALLY_; 027: } 028: 029: { 030: const char *str=av[1]; 031: const char *pattern = av[2]; 032: 033: pcre *preg = NULL; 034: const char *err_str = NULL; 035: int err_offset = 0; 036: 037: apr_file_printf(astdout, "str=[%s]\npattern=[%s]\n", str, pattern); 038: 039: /* 正規表現のコンパイル */ 040: 041: preg = pcre_compile(pattern, 0, &err_str, &err_offset, NULL); 042: 043: if (!preg) { 044: apr_file_printf(astderr, "ERROR: pcre_compile: %s %d ", err_str, err_offset); 045: error_flag = 1; 046: goto _FINALLY_; 047: } 048: 049: /* 文字列のマッチング */ 050: { 051: /* マッチ位置を格納する領域。 052: * (全体マッチの個数1+部分マッチの個数)×3以上確保しないと 053: * pcre_exec の返り値は 0 になる。 054: * 例:日時文字列のマッチング 055: * ^((\d\d\d\d)/(\d\d)/(\d\d))\s+((\d\d):(\d\d):(\d\d)) 056: * の場合、部分マッチが8個あるので、(1+8)×3=27以上。 057: */ 058: int ovector[OVECSIZE]; 059: 060: /* マッチング */ 061: 062: int rc = pcre_exec(preg, NULL, str, strlen(str), 0, 0, ovector, OVECSIZE); 063: 064: if (rc > 0) { 065: int i=0; 066: 067: /* マッチ結果の表示 068: * 全体マッチ: 069: * ovector[0] - 全体マッチの始まりの位置 070: * ovector[1] - 全体マッチの終わりの位置(1バイト前までが含まれる) 071: * 以降は部分マッチ: 072: * ovector[i*2] - 部分マッチの始まりの位置 073: * ovector[i*2+1] - 部分マッチの終わりの位置(1バイト前までが含まれる) 074: */ 075: apr_file_printf(astdout, "Mached:\n"); 076: for (i=0; i<rc; i++) { 077: int start = ovector[i*2]; 078: int end = ovector[i*2 + 1]; 079: apr_file_printf(astdout, "%d: start=%d end=%d [%s]\n", i, start, end, 080: apr_pstrndup(pool, str+start, end-start)); 081: } 082: } else { 083: error_flag = 1; 084: apr_file_printf(astdout, "Not Mached (%d)\n", rc); 085: } 086: } 087: 088: /* 正規表現の開放 */ 089: free(preg); 090: } 091: 092: _FINALLY_: 093: 094: if (error_flag) { 095: apr_file_printf(astderr, "\nfailed.\n"); 096: return 1; /* 異常終了 */ 097: } 098: 099: apr_file_printf(astdout, "\ndone.\n"); 100: return 0; /* 正常終了 */ 101: } 102:
![]() | KAKU PROJECT (2009) |