2015-06-04 100 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