C语言:regexec返回不匹配,即使字符串与模式匹配

huangapple go评论89阅读模式
英文:

C language: regexec returns not matching even the string matches the pattern

问题

static char input[] = "00001415_AXI_7_16";

if (regcomp(&regex, "^\\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;
}

huangapple
  • 本文由 发表于 2023年5月6日 19:36:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定