使用此代码,我创建了一个函数,它接受一个字符串并检查它是否与罗马数相对应(从this thread鼓舞自己)
int checkregex(char *in){
regex_t regex;
char *expression="^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(®ex, expression, 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(®ex, in , 0, NULL, 0);
if (!reti) {
printf("Match\n");
return 1;
}
else if (reti == REG_NOMATCH) {
printf("No match\n");
return 0;
}
else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
return 0;
}
我的问题是它总是返回"没有匹配",所以我想知道我的正则表达式是否与POSIX不兼容,或者我是否错过了其他内容......
有人可以帮助我吗?
答案 0 :(得分:3)
您需要添加REG_EXTENDED
标志,因为您正在使用限制量词而不转义大括号和开始/结束字符串锚点。
请参阅IDEONE demo:
#include <regex.h>
#include <stdio.h>
int checkregex(char *in){
regex_t regex;
char *expression="^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(®ex, expression, REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
return -1;
}
/* Execute regular expression */
reti = regexec(®ex, in , 0, NULL, 0);
if (!reti) {
printf("Match\n");
return 1;
}
else if (reti == REG_NOMATCH) {
printf("No match\n");
return 0;
}
else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
return 0;
}
int main(void) {
int x = checkregex("XII");
printf("%d\n", x);
return 0;
}