我想检查 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/