gpt4 book ai didi

c - 正则表达式没有返回正确的解决方案

转载 作者:行者123 更新时间:2023-11-30 14:54:14 24 4
gpt4 key购买 nike

我正在编写一个 C 程序,它使用正则表达式来确定从文件中读取的文本中的某些单词是否有效。我附上了执行正则表达式检查的代码。我使用了在线正则表达式检查器,据此它说我的正则表达式是正确的。我不知道为什么它会是错误的。
正则表达式应接受 AB1234 或 ABC1234 ABCD1234 格式的字符串。

//compile the regular expression
reti1 = regcomp(&regex1, "[A-Z]{2,4}\\d{4}", 0);
// does the actual regex test
status = regexec(&regex1,inputString,(size_t)0,NULL,0);

if (status==0)
printf("Matched (0 => Yes): %d\n\n",status);
else
printf(">>>NO MATCH<< \n\n");

最佳答案

您正在使用POSIX regular expressions ,来自regex.h。这些不支持您正在使用的语法,即 PCRE格式,并且现在更加常见。您最好尝试使用能为您提供 PCRE 支持的库。如果你必须使用 POSIX 表达式,我认为这会起作用:

#include <regex.h>
#include "stdio.h"
int main(void) {
int status;
int reti1;
regex_t regex1;
char * inputString = "ABCD1234";

//compile the regular expression
reti1 = regcomp(&regex1, "^[[:upper:]]{2,4}[[:digit:]]{4}$", REG_EXTENDED);
// does the actual regex test
status = regexec(&regex1,inputString,(size_t)0,NULL,0);

if (status==0)
printf("Matched (0 => Yes): %d\n\n",status);
else
printf(">>>NO MATCH<< \n\n");

regfree (&regex1);
return 0;
}

(请注意,我的 C 语言非常生疏,因此这段代码可能很糟糕。)

我在 this 上找到了一些很好的资源回答。

关于c - 正则表达式没有返回正确的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46869276/

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