2017-10-22 154 views
0

我正在寫一個C程序,它使用正則表達式來確定正在從文件讀取的文本中的某些單詞是有效還是無效的。我附上了執行我的正則表達式檢查的代碼。我使用了一個在線正則表達式檢查器,並基於它說我的正則表達式是正確的。我不確定爲什麼它會是錯的。
正則表達式應接受AB1234或ABC1234 ABCD1234格式的字符串。正則表達式沒有返回正確的解決方案

//compile the regular expression 
reti1 = regcomp(&regex1, "[A-Z]{2,4}\\d{4}", 0); 
// does the actual regex test 
status = regexec(&regex1,inputString,(size_t)0,NULL,0); 

if (status==0) 
    printf("Matched (0 => Yes): %d\n\n",status); 
else 
    printf(">>>NO MATCH<< \n\n"); 
+1

究竟是「錯誤」呢?請提供可以產生意想不到結果的示例輸入 – aschepler

+1

此外,你可以做一個[簡短但完整的程序](https://stackoverflow.com/help/mcve),說明問題?你應該在代碼中包含至少一個給出意外結果的示例輸入,就像@aschepler提到的那樣,但除此之外,它不需要比你已經擁有'main()'函數的代碼多得多。 –

+1

看起來像使用POSIX正則表達式實現(regex.h),但傳遞不支持的PCRE樣式正則表達式。 –

回答

1

您正在使用POSIX regular expressions,從regex.h。這些不支持您正在使用的語法,格式爲PCRE,而且這些日子更爲常見。你最好試圖使用一個能夠給你PCRE支持的庫。如果你必須使用POSIX表情,我想這會工作:

#include <regex.h> 
#include "stdio.h" 
int main(void) { 
    int status; 
    int reti1; 
    regex_t regex1; 
    char * inputString = "ABCD1234"; 

    //compile the regular expression 
    reti1 = regcomp(&regex1, "^[[:upper:]]{2,4}[[:digit:]]{4}$", REG_EXTENDED); 
    // does the actual regex test 
    status = regexec(&regex1,inputString,(size_t)0,NULL,0); 

    if (status==0) 
     printf("Matched (0 => Yes): %d\n\n",status); 
    else 
     printf(">>>NO MATCH<< \n\n"); 

    regfree (&regex1); 
    return 0; 
} 

(請注意,我的C是非常生疏,所以這段代碼可能是可怕的。)

我發現this回答一些好的資源。