Reputation: 587
checkFormat(string &s)
{
}
string s is a string that indicate the date.
I want to compare a string s, to find whether it is in terms of "yyyy:mm::dd" or not.
What should I do?
compare it char by char? What if the string is "600:12:01" ?
Sorry for my poor English.
Upvotes: 2
Views: 314
Reputation: 399703
Here's one idea for an algorithm:
If either test fails, return false
. If you get through them all, return true
.
Of course, this doesn't validate the ranges of the values. Also, you're not really "comparing", you are "validating".
Upvotes: 2
Reputation: 179779
Don't use regex. Use strptime()
, which is designed to parse time strings (hence the name: str p time
, string -> parse -> time). A regex can't figure out that 2013:2:29
is invalid.
Upvotes: 4
Reputation: 545488
Does your compiler support regular expressions, i.e. are you using a somewhat C++11 compliant compiler? This would make the task much easier … Otherwise you might want to resort to Boost.Regex.
Assuming that you can use C++11, the following code should do what you want (untested though):
std::regex rx("\\d{4}:\\d{2}:\\d{2}");
return regex_match(s.begin(), s.end(), rx);
John Cook has written an introduction into C++ regular expressions. Just replace every occurrence of std::tr1
by std
if your compiler supports C++11.
Upvotes: 0
Reputation: 4317
This is the job for regular expressions. Since you're using C++, Boost.Regex is one option.
Upvotes: 1
Reputation: 258548
You can use Boost Regex to check whether the string matches your pattern.
Upvotes: 1
Reputation: 16476
Easiest would to be slice the string into its component parts of year, month, day and compare those.
See here to split strings by delimiter.
Upvotes: 0