gpt4 book ai didi

c - C 中的正则表达式(使用 regex.h)用于识别罗马数字

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:34 25 4
gpt4 key购买 nike

使用这段代码,我创建了一个函数,它接受一个字符串并检查它是否对应于一个罗马数字(从 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(&regex, expression, 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, 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, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
return 0;

我的问题是它总是返回“不匹配”,所以我想知道我的正则表达式是否与 POSIX 不兼容,或者我是否遗漏了其他东西......

有人能帮帮我吗?

最佳答案

您需要添加 REG_EXTENDED 标志,因为您正在使用限制量词而不转义大括号和开始/结束字符串 anchor 。

参见 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(&regex, expression, REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
return -1;
}

/* Execute regular expression */
reti = regexec(&regex, 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, &regex, 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;
}

关于c - C 中的正则表达式(使用 regex.h)用于识别罗马数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com