Curley大括号在C语言中不能用于正则表达式

use*_*713 4 c regex

Curly大括号{}不能在C语言正则表达式中工作,如果我给出正确的输入为"ab"或"ac",它总是给出输出为NO匹配.在这种情况下我会请求帮助.

 #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, "[a-c]{2}", 0);
        if( reti ){ fprintf(stderr, "Could not compile regex\n"); return(1); }

        /* Execute regular expression */
        reti = regexec(&regex, "ab", 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;
}
Run Code Online (Sandbox Code Playgroud)

hal*_*lex 6

您正在使用基本正则表达式方言,该方言不了解{n}正则表达式中的量词.

一种解决方案是REG_EXTENDED在创建regex_t对象时将选项作为最后一个参数而不是0 .

reti = regcomp(&regex, "[a-c]{2}", REG_EXTENDED);
Run Code Online (Sandbox Code Playgroud)

有关我的修改,请参阅http://ideone.com/oIBXxu以获取代码演示.


正如Casimir et Hippolyte在评论中指出的那样,Basic Regular Expressions也支持{}量词,但是花括号必须用\正则表达式中的a进行转义,再次必须在C字符串中转义为\\.所以你可以使用这条线

reti = regcomp(&regex, "[a-c]\\{2\\}", 0);
Run Code Online (Sandbox Code Playgroud)

以及上述解决方案的替代方案(在http://ideone.com/x7vlIO下修改此行的Demo ).

您可以查看http://www.regular-expressions.info/posix.html,了解有关Basic和Extended Regular Expressions之间区别的更多信息.