在C语言中,花括号在正则表达式中无法正常工作。

4

在C语言中的正则表达式中,花括号{}无法正常工作,无论我输入“ab”或“ac”,它都会输出“NO match”。请帮助解决这个问题。

 #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;
}
1个回答

6

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

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

reti = regcomp(&regex, "[a-c]{2}", REG_EXTENDED);

请参考http://ideone.com/oIBXxu以查看我修改后的代码演示。


正如Casimir和Hippolyte在评论中指出的,基本正则表达式也支持{}量词,但是花括号必须在正则表达式中使用\进行转义,在C字符串中再次进行转义为\\。因此,您可以使用以下代码:

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

除了上述解决方案(在http://ideone.com/x7vlIO下修改此行并运行演示)之外,还有一个替代方案。

您可以查看http://www.regular-expressions.info/posix.html以获取有关基本正则表达式和扩展正则表达式之间区别的更多信息。


是的,否则您可以始终使用BRE语法:reti = regcomp(&regex, "[a-c]\\{2\\}", 0); - Casimir et Hippolyte
非常感谢您的回答。问题已经解决了。 - user1720713
1
C语言中的BRE有{n}量词,你只需要转义花括号即可。http://ideone.com/x7vlIO - Casimir et Hippolyte
@user1720713,你又忘记在正则表达式开头加上^和结尾加上$来匹配整行了。 - halex
但实际上我需要实现的正则表达式是:"[0-9a-f]{4}\. [0-9a-f]{4}\. [0-9a-f]{4}";在这种情况下,我该如何使用^和$? - user1720713
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接