2013-03-07 87 views
3
#include <stdio.h> 
#include <string.h> 
#include <pcre.h> 
#define OVECCOUNT 30 
#define SRCBUFFER 1024*1024 

int main(int argc, char **argv){ 
pcre *re; 
const char *error; 
int erroffset; 
int ovector[OVECCOUNT]; 
int rc, i; 
if (argc != 2){ 
    fprintf(stderr, "Usage : %s PATTERN\n", argv[0]); 
    return 1; 
} 

char *src=malloc(SRCBUFFER); 
int srclen = fread(src, sizeof(char), SRCBUFFER, stdin); 
re = pcre_compile(argv[1], 0, &error, &erroffset, NULL); 
if (re == NULL){ 
    fprintf(stderr, "PCRE compilation failed at offset %d: %s\n", erroffset, error); 
    return 1; 
} 

rc = pcre_exec(re, NULL, src, srclen, 0, 0, ovector, OVECCOUNT); 
if (rc < 0){ 
    if (rc == PCRE_ERROR_NOMATCH) fprintf(stderr, "Sorry, no match...\n"); 
    else fprintf(stderr, "Matching error %d\n", rc); 
    return 1; 
} 

for (i = 0; i < rc; i++){ 
    char *substring_start = src + ovector[2 * i]; 
    int substring_length = ovector[2 * i + 1] - ovector[2 * i]; 
    fprintf(stdout, "%2d: %.*s\n", i, substring_length, substring_start); 
} 
return 0; 
} 

來看,它PCRE C API只返回第一個匹配

回聲 「蘋果香蕉非洲」 | ./program '\ BA \ w + \ B'

,並將其打印

0:蘋果

我試圖使用PCRE_MULTILINE選項,但沒有use.How讓它打印所有比賽?

+0

你的I/O完全沒有錯誤檢查,你甚至不知道你設法讀取超過「蘋果」。 – unwind 2013-03-07 12:18:46

+0

我補充一些,它返回: – riaqn 2013-03-07 12:22:56

+0

\ BA \ w + \ b 蘋果香蕉非洲 0:蘋果 – riaqn 2013-03-07 12:23:08

回答

2

這聽起來像你正在尋找的是相當於Perl /g正則表達式標誌重複匹配儘可能多次並返回所有匹配的結果。我不相信PCRE有這樣的事情。

相反,您需要添加一個圍繞pcre_exec的循環。每次調用它時,都會返回匹配開始和結束的字節偏移量。然後,您希望再次在比賽結束時的字符串上運行pcre_exec。重複,直到pcre_exec不匹配。

相關問題