在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(®ex, "[a-c]{2}", 0);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); return(1); }
/* Execute regular expression */
reti = regexec(®ex, "ab", 0, NULL, 0);
if( !reti ){
puts("Match");
}
else if( reti == REG_NOMATCH ){
puts("No match");
}
else{
regerror(reti, ®ex, 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(®ex);
return 0;
}
reti = regcomp(®ex, "[a-c]\\{2\\}", 0);
- Casimir et Hippolyte{n}
量词,你只需要转义花括号即可。http://ideone.com/x7vlIO - Casimir et Hippolyte^
和结尾加上$
来匹配整行了。 - halex