Reputation: 61
I'm currently working to parse dates into a program.
The format can be in the following form:
DDMMYYYY
DDMMYY
DDMM
DD/MM/YYYY
DD/MM/YY
DD/MM
Do that that along with the dates, there would be other content included such as the follows:
19/12/12 0800 1000
That breaks my current implementation of using boost::date_time and tokenizer.
For the situation, what would the best suggestion? Would I be able to have a better implementation that would allow the following:
19 Sep 12 // DD MMM YY
What I had in mind was to return them as strings in the form DDMMYYYY form for use in other parts of the program. Is this the best way or are there better suggestion/alternatives?
*EDIT:
Decided that taking DDMMYYYY, DDMMYY & DDMM isn't that feasible. Shall only go with dates with backslashes.
The output remains the same though, strings in the format : DDMMYYYY
Upvotes: 2
Views: 3383
Reputation: 1513
The following code works for me.
regex regExDate("\\d{4}-\\d{2}-\\d{2}");
string date = "abc:\\2016-09-12";
smatch match;
if (regex_search(date, match, regExDate))
{
string strDate = match.str();
}
Upvotes: 0
Reputation: 8421
Using boost.regex, you can do the following:
#include <iostream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
regex re("(\\d{2})\\/(\\d{2})(?:\\/?(\\d{2,4}))?");
cmatch m;
regex_search("1234 10/10/2012 4567", m, re);
cout << m.str(1) + m.str(2) + m.str(3) << endl;
regex_search("1234 10/10/12 4567", m, re);
cout << m.str(1) + m.str(2) + m.str(3) << endl;
regex_search("1234 10/10 4567", m, re);
cout << m.str(1) + m.str(2) << endl;
return 0;
}
Compile like this:
g++ --std=c++11 -o test.a test.cpp -I[boost_path] [boost_path]/stage/lib/libboost_regex.a
Upvotes: 2
Reputation: 1254
You can use some regexp library or builtin sscanf function. It is more primitive than reg exp but can be used in your case
/* sscanf example */
#include <stdio.h>
int main ()
{
char sentence []="data 1";
char str [16];
int i;
sscanf(sentence,"%s %d",str,&i);
printf("%s -> %d\n",str,i);
return 0;
}
Upvotes: 0