2015-06-04 35 views
-1

Or運算符(|)不能用C語言正則表達式,它總是給出匹配的輸出,如果我給不正確的輸入也是「12」或「 123「或c顯示爲MATCH。我會請求在這種情況下提供幫助。| (或者運算符在C語言的正則表達式中不起作用)

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


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

    /* Compile regular expression */ 
    reti = regcomp(&regex, "1 | 2c | 3c", REG_EXTENDED); 
    if(reti){ fprintf(stderr, "Could not compile regex\n"); return(1); } 

    /* Execute regular expression */ 
    reti = regexec(&regex, "123", 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); 
      return 1; 
    } 

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

    return 0; 

}

+0

沒有標準的「C語言正則表達式」。你在使用哪個庫? –

+2

小心正則表達式中的空格,正則表達式中的所有字符都很重要。您可能還需要對子表達式進行分組,因爲正則表達式不具有任何種類的運算符優先級。 –

+1

[不匹配]​​(「http://ideone.com/plXXVZ)」和「123」。用「2c」,[有一個匹配](http://ideone.com/qtSrfl)。那麼問題是什麼? –

回答

0

你的正則表達式匹配1 | 2c | 3cI have 1 dollar1,但是從你的意見,我看你需要匹配整個字符串,而不是隻是其中的一部分。爲此,您需要使用錨點^(字符串的開始)和$(字符串的結尾),僅在使用REG_EXTENDED標誌時才起作用。

當您使用的替代品,你需要重複上述錨,或設置一組用括號的幫助:

^1$|^2c$|^3c$ 

或者

^(1|2c|3c)$ 

這些表達式will safely match whole strings12c,或3c