2014-02-05 13 views
1

的代碼不匹配:正則表達式使用C時的egrep確實

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

int main() { 
    unsigned i; 
    regex_t regex; 
    regmatch_t captures[2]; 
    char *  nmLines[] = { 
     "0000000000000a10 t frame_dummy", 
     "0000000000000a40 T geom_Init", 
     "0000000000000b30 t geom_RectangleAllocate", 
    }; 
    int errCode = regcomp(&regex, ".*\\W(\\w+_Init)\\W*", 0); 
    if(errCode) { 
     char errMsg[1024]; 
     regerror(errCode, &regex, errMsg, sizeof(errMsg)); 
     fprintf(stderr, "%s\n", errMsg); 
     return 1; 
    } 
    for(i = 0U; i < sizeof(nmLines)/sizeof(nmLines[0]); ++i) { 
     errCode = 
     regexec(
      &regex, 
      nmLines[i], 
      sizeof(captures)/sizeof(captures[0]), 
      captures, 
      0); 
     if(0 == errCode) { 
     printf("Match : %s, between %d and %d\n", 
      nmLines[i], captures[1].rm_so, captures[1].rm_eo); 
     } 
     else { 
     printf("Doesn't match : %s\n", nmLines[i]); 
     } 
    } 
    regfree(&regex); 
    return 0; 
} 

輸出:

$ gcc -W -Wall -o rx rx.c ; ./rx 
Doesn't match : 0000000000000a10 t frame_dummy 
Doesn't match : 0000000000000a40 T geom_Init 
Doesn't match : 0000000000000b30 t geom_RectangleAllocate 

相同的輸出過濾,用(正確的)的egrep至極匹配一條線3之間:

$ ./rx | egrep '.*\W(\w+_Init)\W*' 
Doesn't match : 0000000000000a40 T geom_Init 
$ 

爲什麼regexec失敗時egrep成功具有相同的表達?

+1

的GNU擴展沒有保證您的'regex'庫支持同一正則表達式的語法'egrep'。您需要閱讀庫的文檔,並確保您使用的是一致的正則表達式。 – larsks

+0

這是什麼'sizeof(captureures)/ sizeof(captures [0])'?只有一個捕獲組是正確的? – sln

+0

在這種情況下,sizeof(captures)/ sizeof(captures [0])返回2:一個用於整個表達式,一個用於捕獲 – Aubin

回答

0

我的錯誤是固定使用更復雜的正則表達式的功能時,又是一個有用的標誌!

我使用的表達POSIX擴展正則表達式不是POSIX基本正則表達式

修訂代碼:

int errCode = regcomp(&regex, ".*\\W(\\w+_Init)\\W*", REG_EXTENDED); 

Here is an extract of the documentation:

  • REG_EXTENDED:使用POSIX擴展正則表達式(ERE)語法解釋的正則表達式時。如果未設置,則使用POSIX基本正則表達式(BRE)語法。

regcomp因爲表達是有效的BRE但已經沒有意義了,因爲\W不作爲單詞邊界和\w作爲一個詞的一部分行爲不報告錯誤。這些字符與一樣是

Here is another helpful documentation有關ERE\W\w

+0

這是否解決了它? – sln

-1

有多個標誌,你可以使用正則表達式的功能時,對POSIX看到http://linux.die.net/man/3/regexec
我認爲是造成你的問題之一是
REG_ICASE
不區分情況設置。後續使用此模式緩衝區的regexec()搜索將不區分大小寫。

REG_EXTENDED
在C

+0

不,我正在尋找精確匹配,而不是大小寫不敏感的匹配。 – Aubin

+0

也許你可以嘗試擴展的語法標誌,然後...或W的完整形式是[^ \ w] ... – clancer