AlphaProgrammer AlphaProgrammer - 2 months ago 19
C++ Question

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. It always return's
false
.
*



  • I am running the console application on 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;
}

Answer

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. Something more like:

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

...I think should make you good anywhere in recent centuries ;-)