C 编程中使用正则表达式检查字符串是否全是字母数字

标签 c regex alphanumeric

我想检查 C 中的字符串是否仅包含字母数字字符。我不想使用 isalnum 函数。为什么下面的代码不能正常工作?

int main()
{
    printf("test regular expression\n");
    int retval = 0;
    regex_t re;
    char line[8] = "4a.zCCb";
    char msgbuf[100];
    if (regcomp(&re,"[a-zA-z0-9]{2,8}", REG_EXTENDED) != 0)
    {
        fprintf(stderr, "Failed to compile regex '%s'\n", tofind);
        return EXIT_FAILURE;
    }
    if ((retval = regexec(&re, line, 0, NULL, 0)) == 0)
        printf("Match : %s\n", line);
    else  if (retval == REG_NOMATCH)
        printf("does not match : %s\n", line);
    else {
        regerror(retval, &re, msgbuf, sizeof(msgbuf));
        fprintf(stderr, "Regex match failed: %s\n", msgbuf);
        exit(1);
    }
    regfree(&re);
}

最佳答案

如果您希望整个字符串为字母数字,则需要在正则表达式中包含开始和结束 anchor :

"^[a-zA-Z0-9]{2,8}$"

就目前情况而言,字符串末尾有 4 个字母数字,与原始正则表达式匹配。

关于C 编程中使用正则表达式检查字符串是否全是字母数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24773220/

相关文章:

regex - 使用 Perl 和 Regex 将文件名排序到数组中

sql - 排序字母数字列

c - C : Binary files 上的文件操作

c - freopen 或 freopen_s,它们到底在做什么?

c# - C# 是否具有与#def 常量等效的#include?

java - 递归回文测试不能包含特殊字符

python - 识别包含数字和字符串的 pandas 数据框列

c - 我收到一个 SegFault 错误,但为什么呢?

ruby 正则表达式和分组

r - 如何在 R 中的字符串中添加缺少的右括号?