2013-10-12 14 views
6

Tôi đang sử dụng | để lựa chọn thay thế nhưng không hoạt động. Tôi có làm điều gì sai?POSIX regex thay thế không hoạt động

Cảm ơn!

Các mã sau đây luôn luôn trả 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

Bạn có thử '\ |'? – JimR

+0

Chỉ cần thử, không hoạt động – ethanjyx

+0

Một số thư viện regex muốn thoát cho '|', '+' etc ... – JimR

Trả lời

7

Khi POSIX manual nói, bạn cần phải thiết lập các tham số cờ để cho phép biểu thức thông thường kéo dài.

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; đó chính là vấn đề. –

Các vấn đề liên quan