2013-10-12 33 views
6

我使用|替代方案,但它不起作用。難道我做錯了什麼?POSIX正則表達式替代方案不起作用

謝謝!

下面的代碼總是返回No match

#include <sys/types.h> 
#include <regex.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 

int main(int argc, char *argv[]){ 
     regex_t regex; 
     int reti; 
     char msgbuf[100]; 

/* Compile regular expression */ 
     reti = regcomp(&regex, "ab(c|d)", 0); 
     if(reti){ fprintf(stderr, "Could not compile regex\n"); exit(1); } 

/* Execute regular expression */ 
     reti = regexec(&regex, "abd", 0, NULL, 0); 
     if(!reti){ 
       puts("Match"); 
     } 
     else if(reti == REG_NOMATCH){ 
       puts("No match"); 
     } 
     else{ 
       regerror(reti, &regex, msgbuf, sizeof(msgbuf)); 
       fprintf(stderr, "Regex match failed: %s\n", msgbuf); 
       exit(1); 
     } 

/* Free compiled regular expression if you want to use the regex_t again */ 
    regfree(&regex); 

     return 0; 

} 
+0

你嘗試'\ |'? – JimR

+0

剛剛嘗試過,不工作 – ethanjyx

+0

一些正則表達式庫需要'|','+'等的轉義... – JimR

回答

7

由於POSIX manual說,你需要設置flags參數允許擴展正則表達式。

REG_EXTENDED 
      Use POSIX Extended Regular Expression syntax when interpreting 
      regex. If not set, POSIX Basic Regular Expression syntax is 
      used. 
+0

+1:Spot on;這正是問題所在。 –