c++ boost regex日期错误

C++ boost regex date error

本文关键字:错误 日期 regex boost c++      更新时间:2023-10-16

我对增强正则表达式库很陌生。下面的示例代码用于检查输入的日期是否遵循YYYY-MM-DD格式。然而,在正则表达式中似乎有一个错误。它总是返回false。*

    我正在windows上运行控制台应用程序。

*正则表达式取自此处

bool regexValidate(string teststring)
{
boost::regex ex("^(20\d{2})(\d{2})(\d{2})");
if (boost::regex_match(teststring, ex)) {
    cout << "true";
    return true;
}
else {
    return false;
}
}
 int main()
{

string  teststr = "2016-05-15";

cout << teststr << " is ";
if (regexValidate( teststr)) {
    cout << " valid!" << endl;
}
else {
    cout << " invalid!" << endl;
}
system("PAUSE");
return 0;
 }

你就快成功了;只需在regex中添加连字符:

"^(20\d{2})-(\d{2})-(\d{2})"

顺便说一句,这不会解析2000年之前或2099年之后的日期。并且在末尾没有显式的字符串结束符($)。更像是:

"^(\d{4})-(\d{2})-(\d{2})$"

…我想应该能让你在最近几个世纪的任何地方都表现出色;-)