在 c 中执行时正则表达式不起作用

regular expression doesnt work while execute in c

我正在尝试使用 regex.h 库构建正则表达式。

我在 https://regex101.com/ 中用输入检查了我的表达 “00001206 ffffff00 00200800 00001044”,我也在 python 中检查了它,都给了我预期的结果。 当我 运行 下面的 c 代码(在 unix 上)时,我得到了 "no match" 打印。 有人有什么建议吗?

regex_t regex;
int reti;
reti = regcomp(&regex, "([0-9a-fA-F]{8}( |$))+$", 0);
if (reti) 
{
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

reti = regexec(&regex, "00001206 ffffff00 00200800 00001044", 0, NULL, 0);
if (!reti) 
{
     printf("Match");
 }
  else if (reti == REG_NOMATCH) {
  printf("No match bla bla\n");
   }  

您的模式包含一个 $ 锚点,使用 (...) 和区间量词 {m,n} 捕获组,因此您需要将 REG_EXTENDED 传递给正则表达式编译方法:

regex_t regex;
int reti;
reti = regcomp(&regex, "([0-9a-fA-F]{8}( |$))+$", REG_EXTENDED); // <-- See here
if (reti) 
{
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

reti = regexec(&regex, "00001206 ffffff00 00200800 00001044", 0, NULL, 0);
if (!reti) 
{
    printf("Match");
}
else if (reti == REG_NOMATCH) {
    printf("No match bla bla\n");
}  

查看 online C demo 打印 Match

不过,我相信你需要匹配整个字符串,并且不允许在末尾出现白色space,所以可能

reti = regcomp(&regex, "^[0-9a-fA-F]{8}( [0-9a-fA-F]{8})*$", REG_EXTENDED);

会更精确,因为它不允许前面有任何文本,也不允许尾随 space。