当我在 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 (®ex, regPatt, 0);
short status = regexec (®ex, "HR16", (size_t) 0, NULL, 0);
printf ("%hd", status);
regfree (®ex);
}
所以,在线测试工作得很好。
正则表达式 - ^HR(\d{2})$
字符串 - HR16
At https://regex101.com例如,一切都很好,我得到了一场比赛。
在我的代码中,它失败了。使用 printf() 打印的值为 1 (REG_NOMATCH)。
编辑 - 可以将代码粘贴到此处进行测试:https://rextester.com/l/c_online_compiler_gcc
你应该使用[0-9]
代替\d
并通过REG_EXTENDED
to the regcomp
功能。
REG_EXTENDED
解释正则表达式时使用 POSIX 扩展正则表达式语法。如果未设置,则使用 POSIX 基本正则表达式语法。
这里是更新的代码:
#include <stdio.h>
#include <regex.h>
int main(void)
{
char *regPatt = regPatt = "^HR([0-9]{2})$";
regex_t regex;
short retval = regcomp (®ex, regPatt, REG_EXTENDED);
short status = regexec (®ex, "HR16", (size_t) 0, NULL, 0);
printf ("%hd", status);
regfree (®ex);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)