我正在尝试使用正则表达式检查字符串是否为整数。我认为模式应该是 ^\d$
并且我编写了一个函数来在参数不合适时打印错误:
regex_t regex;
void check_int(char *c)
{
check=regcomp(®ex,"^\d$",0);
if (check!=0)
{
perror("4th element on the line is not an integer!");
exit(5);
}
else printf("4th arg is a number.");
}
我不确定 regcomp
是如何工作的,我在检查互联网上的一些示例后按照我认为应该使用的方式使用了它。
问题是它总是说我的字符串是一个数字,不知道为什么...
添加了这个,现在总是返回不匹配:
status = regexec(®ex, c, (size_t) 0, NULL, 0);
refree(®ex);
if(status!=0)
{
perror("..");
exit(5);
}
最佳答案
你的例子有几个问题:
regcomp
仅准备正则表达式(检查 documentation : “regcomp()
函数应编译包含在指向的字符串中的正则表达式模式参数...”)- 根据documentation我假设你的正则表达式是
"^[[:digit:]+]$"
- 你的字符串以
\n
结束,所以这里的结束 anchor 不匹配 - 你必须评估result of
regcomp
为了评估匹配项(“如果找到匹配项,regexec()
应返回 0;否则,它应返回非零值,指示......”) 如果尾随空格也适合您,请另外使用
[:space:]
void check_int(char *c) { int check=regcomp(®ex,"^[[:digit:]+]$",0); int status = regexec(®ex, c, (size_t) 0, NULL, 0); if (status !=0) { ....
检查键盘上的 full example .
关于C 正则表达式,regcomp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29182038/