Regular Expressions are not returning correct 解决办法

Regular Expressions are not returning correct solution

我正在编写一个 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, from regex.h. These don't support the syntax you are using, which is 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 答案中找到了一些很好的资源。