正则表达式在 C 中失败,在线测试通过 [英] Regex fails in C, online tests pass
问题描述
当我在 C 中使用它时应该工作的正则表达式失败.
A regex that should work fails when I use it in C.
当我在此处粘贴此正则表达式时 - https://regex101.com 并按预期测试它似乎没问题.
When I paste this regex here - https://regex101.com and test it it seems fine, as expected.
//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);
}
所以,在线测试工作正常.
So, online test work just fine.
正则表达式 - ^HR(\d{2})$
Regex - ^HR(\d{2})$
字符串 - HR16
例如在 https://regex101.com,一切都很好,我得到了匹配.
At https://regex101.com for example, all is fine, I get a match.
在我的代码中,它失败了.printf() 打印的值为 1 (REG_NOMATCH).
In my code, it fails. Value printed with printf() is 1 (REG_NOMATCH).
编辑 - 可以将代码粘贴到此处进行测试:https://rextester.com/l/c_online_compiler_gcc
edit - the code can be pasted for a test here: https://rextester.com/l/c_online_compiler_gcc
推荐答案
你应该使用 [0-9]
而不是 \d
并通过 REG_EXTENDED
到 regcomp
函数.
You should use [0-9]
instead of \d
and pass REG_EXTENDED
to the regcomp
function.
REG_EXTENDED
解释正则表达式时使用 POSIX 扩展正则表达式语法.如果未设置,则使用 POSIX 基本正则表达式语法.
REG_EXTENDED
Use POSIX Extended Regular Expression syntax when interpreting regex. If not set, POSIX Basic Regular Expression syntax is used.
这是更新代码:
#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);
}
这篇关于正则表达式在 C 中失败,在线测试通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!