简体   繁体   English

C++ 提升正则表达式日期错误

[英]C++ boost regex date error

I am quite new to boost regex library.The following sample code is used to check if the entered date is following the YYYY-MM-DD format.However,there seems to be an error in the regex.我对 boost regex 库很陌生。以下示例代码用于检查输入的日期是否遵循YYYY-MM-DD格式。但是,regex 中似乎存在错误。 It always return's false .它总是返回false * *

  • I am running the console application on windows.我在 Windows 上运行控制台应用程序。

* the regex was taken from here * 正则表达式取自此处

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;
 }

You're almost there;您快到了; just add hyphens to your regex:只需在正则表达式中添加连字符:

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

BTW, this won't parse dates before 2000 or after 2099. And there's no explicit end-of-string ($) at the end.顺便说一句,这不会解析 2000 年之前或 2099 年之后的日期。并且最后没有明确的字符串结尾 ($)。 Something more like:更像是:

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

...I think should make you good anywhere in recent centuries ;-) ...我认为应该让你在最近几个世纪的任何地方都很好;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM