英文:
C language: regexec returns not matching even the string matches the pattern
问题
static char input[] = "00001415_AXI_7_16";
if (regcomp(®ex, "^\\d{1,8}_[A-Z]{3}_(\\*|\\d{1,3})_(\\*|\\d{1,3})$",
REG_EXTENDED | REG_NOSUB))
{
fprintf(stderr, "Error during creating regex\n");
return false;
}
英文:
I use regex in the C language. I have the following code:
#include <regex.h>
static char input[] = "00001415_AXI_7_16";
static bool checkSn(char *input)
{
regex_t regex;
if (regcomp(&regex, "^\\d{1,8}_[A-Z]{3}_(\\*|\\d{1,3})_(\\*|\\d{1,3})$",
REG_EXTENDED))
{
fprintf(stderr, "Error during creating regex\n");
return false;
}
if (regexec(&regex, input, 0, NULL, 0))
{
return false;
}
return true;
}
I can compile the program without any warning. I can run the program, but the function returns false even the input string matches the regular expression, I tried it obviously at an online regular expression tester. Could you please help me where is a mistake?
Thank you in advance.
I tried few flags for the regcomp function. I tried the regular expression without "^" and without "$" with the same result.
答案1
得分: 0
你使用 REG_EXTENDED
标志进行编译。然而,当前使用的正则表达式是基本正则表达式语法。
你可以将正则表达式更改为使用扩展语法,或者可以从 regcomp 函数调用中删除 REG_EXTENDED
标志。
使用扩展版本:
if (regcomp(&regex, "^[[:digit:]]{1,8}_[[:upper:]]{3}_(\\*|[[:digit:]]{1,3})_(\\*|[[:digit:]]{1,3})$",
REG_EXTENDED))
{
fprintf(stderr, "Error during creating regex\n");
return false;
}
或者不使用:
if (regcomp(&regex, "^[0-9]\\{1,8\\}_[A-Z]\\{3\\}_\\(\\*\\|[0-9]\\{1,3\\}\\)_\\(\\*\\|[0-9]\\{1,3\\}\\)$",
0))
{
fprintf(stderr, "Error during creating regex\n");
return false;
}
英文:
You compile with REG_EXTENDED
flag. However, the current regular expression using is the basic regular expression syntax.
You can change the regular expression to use the extended syntax, or you can remove the REG_EXTENDED
flag from the regcomp function call.
With extended version:
if (regcomp(&regex, "^[[:digit:]]{1,8}_[[:upper:]]{3}_(\\*|[[:digit:]]{1,3})_(\\*|[[:digit:]]{1,3})$",
REG_EXTENDED))
{
fprintf(stderr, "Error during creating regex\n");
return false;
}
Or without:
if (regcomp(&regex, "^[0-9]\\{1,8\\}_[A-Z]\\{3\\}_\\(\\*\\|[0-9]\\{1,3\\}\\)_\\(\\*\\|[0-9]\\{1,3\\}\\)$",
0))
{
fprintf(stderr, "Error during creating regex\n");
return false;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论