我需要验证用户输入的日期格式是否为 MM/YYYY。
我决定使用 regcomp 和 regexec 函数作为我的解决方案。
问题是:无论输入什么,输出都是总是匹配。 调用 regexec 的返回值为 0,表示匹配,即使实际上没有匹配。
为什么会这样?
我知道我使用的正则表达式将匹配 99/99,但我首先试图弄清楚为什么它也匹配 ABCDE。
下面是有问题的代码:
#include <iostream>
#include <cstring>
#include <regex.h>
using namespace std;
int main(int argc, char ** argv)
{
int rs;
regex_t preg;
size_t nmatch = 1;
regmatch_t pmatch[1];
char * pattern = "^((0[1-9])|(1[0-2]))\/(\d{4})$";
char inputDate[8];
//Loop until user input matches regex
cout << "Enter Date: ";
cin.getline(inputDate, 8);
if (0 != (rs = regcomp(&preg, pattern, 0))) {
perror("ERROR IN REGCOMP");
exit(1);
}
if (0 != (rs = regexec(&preg, inputDate, nmatch, pmatch, 0))) {
printf("Failed to match '%s' with '%s',returning %d.\n", inputDate, pattern, rs);
perror("ERROR IN REGEXEC");
}
else
printf("Match");
return 0;
}
最佳答案
首先你的正则表达式必须是 "^[0-9][0-9]\\/[0-9][0-9][0-9][0-9]$"
以匹配 MM/YYYY
。
第二,你永远不会编译它。您编译 inputDate。
regcomp(&preg, inputDate, REG_EXTENDED)
尝试编译你的模式:
regcomp(&preg, pattern, REG_EXTENDED)
关于c++ - 确保用户输入的日期是 (MM/YY),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36751053/