2014-11-21 19 views
2

我試圖編寫一個簡單的c程序來檢查路徑名是否帶有「.jpg」或「.jpeg」後綴。這是我的程序:問題標記(?)在正則表達式中不起作用

#include <stdio.h> 
#include <string.h> 
#include <regex.h> 

regex_t regex; 

static int is_acceptable_format(const char *path) { 
    int reti = regexec(&regex, path, 0, NULL, 0); 

    if (!reti) { 
     return 1; 
    } else if (reti == REG_NOMATCH) { 
     return 0; 
    } else { 
     char msgbuf[100]; 
     regerror(reti, &regex, msgbuf, sizeof(msgbuf)); 
     printf("Regex match failed: %s\n", msgbuf); 

     return 0; 
    } 
} 

static void init_accpetable_format() { 
    if (regcomp(&regex, "\\.JP(E?)G$", REG_ICASE)) { 
     printf("Could not compile regex\n"); 
    } 
} 

main() 
{ 
    const char *path = "/sample_img.jpg"; 
    init_accpetable_format(); 
    printf("path=\"%s\" is %s\n", 
     path, is_acceptable_format(path) ? "acceptable" : "unacceptable"); 
} 

我希望我的程序返回「可接受」,但它返回「不可接受」,而不是。如果我讓我的正則表達式爲「\ .JPG $」,結果就變成了「可接受的」。

我以爲正則表示的問號(?)表示0或1次regex rule。但爲什麼它不工作?

回答