简体   繁体   English

为什么正则表达式总是返回1?

[英]Why regex always returns 1?

The following function checks if a variable name start with a letter and may have preceding characters which are letters/ numbers. 以下函数检查变量名称是否以字母开头,并且可能具有字母/数字的前面的字符。 Why does the return value is always 1 no matter what the input is? 无论输入是什么,为什么返回值始终为1?

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

int validate_var(char *str)
{
    regex_t reg;
    regcomp(&reg, "^[a-zA-Z]+[a-zA-Z0-9]*$", 0);
    int r = regexec(&reg, str, 0, NULL, 0);
    regfree(&reg);

    return r;
}

int main() {
    printf("%d\n", validate_var("abc")); // Reports 1, This makes sense
    printf("%d\n", validate_var("17"));  // Reports 1, This doesn't make sense
}

You're using anchors ( ^ and $ ) but not enabling extended syntax by passing REG_EXTENDED to regcomp() . 您正在使用锚点( ^$ ),但不通过将REG_EXTENDED传递给regcomp()来启用扩展语法。 See the manual page . 请参见手册页

You should really check all return values, there should be a failure reported somewhere due to the syntax usage error. 您应该检查所有返回值,由于语法使用错误,应该在某处报告失败。

Note that non-zero means failure. 请注意,非零意味着失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM