【问题标题】:Regex fails in C, online tests pass正则表达式在 C 语言中失败,在线测试通过
【发布时间】:2026-02-02 11:40:01
【问题描述】:

当我在 C 中使用时,一个应该可以工作的正则表达式失败了。

当我在此处粘贴此正则表达式 - https://regex101.com 并对其进行测试时,它看起来不错,正如预期的那样。

//clang 3.8.0

#include  <stdio.h>
#include  <regex.h>

int main(void)
{
   char    *regPatt = regPatt = "^HR(\\d{2})$";
   regex_t  regex;
   short    retval = regcomp (&regex, regPatt, 0);
   short    status = regexec (&regex, "HR16", (size_t) 0, NULL, 0);

   printf ("%hd", status);

   regfree (&regex);
}

所以,在线测试工作正常。

正则表达式 - ^HR(\d{2})$

字符串 - HR16

例如在https://regex101.com,一切都很好,我得到了匹配。

在我的代码中,它失败了。使用 printf() 打印的值为 1 (REG_NOMATCH)。

编辑 - 可以将代码粘贴到此处进行测试:https://rextester.com/l/c_online_compiler_gcc

【问题讨论】:

  • 次要注意:您为什么使用char *regPatt = regPatt = "^HR(\\d{2})$"; 而不仅仅是char *regPatt = "^HR(\\d{2})$";?为什么要多出regPatt =
  • 您使用的是基本的正则表达式(没有 REG_EXTENDED 标志),因此 {2} 是按字面意思解释的。试试"^HR[0-9][0-9]$"

标签: c regex


【解决方案1】:

您应该使用[0-9] 而不是\d 并将REG_EXTENDED 传递给regcomp 函数。

REG_EXTENDED
解释正则表达式时使用 POSIX 扩展正则表达式语法。如果未设置,则使用 POSIX 基本正则表达式语法。

这里是updated code

#include  <stdio.h>
#include  <regex.h>

int main(void)
{
   char    *regPatt = regPatt = "^HR([0-9]{2})$";
   regex_t  regex;
   short    retval = regcomp (&regex, regPatt, REG_EXTENDED);
   short    status = regexec (&regex, "HR16", (size_t) 0, NULL, 0);
   printf ("%hd", status);
   regfree (&regex);
}

【讨论】:

  • 给魔鬼应得的+1
  • 我在代码中使用了 REG_EXTENDED 和其他一些标志,但它们都没有改变结果。如果我这样输入:[0-9][0-9] 那么很好。 [0-9]{2} 失败。去图吧。
  • 顺便说一句,这是demo on the rextester。不确定你是否需要它,但这里有一个C code to extract Group 1 value
  • 测试了你的代码,只好改一行,regmatch_t pmatch[2];它似乎有效,我的编译器似乎是问题所在。可能是 gcc 的旧版本,因为它在 rextester.com/l/c_online_compiler_gcc 的在线编译器上运行良好 - 我可以接受您的解决方案,即使它没有帮助我:(