|
Boost Users : |
From: Andrew Holden (aholden_at_[hidden])
Date: 2006-03-21 17:17:53
> -----Original Message-----
> From: Christian Henning [mailto:chhenning_at_[hidden]]
> Sent: Tuesday, March 21, 2006 4:23 PM
> To: boost-users_at_[hidden]
> Subject: Re: [Boost-users] [date_time] How to create a date from
string
> withspecific format?
>
> Hi Dean, thanks for the answer.
>
> Since, I know the format of the date strings I could also use
> boost::regex for the general format and then feeding a date object
> with the values. If I get an exception during the date object
> contruction I know that the user provided me with garbage.
>
>
> Any thoughts on that?
>
> Thanks again,
> Christian
Have you considered using Regex's submatches? A slightly modified
example follows.
// date format: mm-dd-yyyy
boost::regex oDateReg( "(\\d{2})-(\\d{2})-(\\d{4})" );
std::string strDate( "11-33-1997" );
boost::smatch dateMatch;
if( boost::regex_match( strDate
, dateMatch
, oDateReg ))
{
try
{
std::string strMonth = dateMatch[1];
std::string strDay = dateMatch[2];
std::string strYear = dateMatch[3];
unsigned int nYear = boost::lexical_cast<unsigned
int>(strYear);
unsigned int nMonth = boost::lexical_cast<unsigned
int>(strMonth);
unsigned int nDay = boost::lexical_cast<unsigned
int>(strDay);
date d( nYear, nMonth, nDay );
date::ymd_type ymd = d.year_month_day();
}
catch( std::out_of_range oEx )
{
std::cout << "Error: " << oEx.what() << std::endl;
}
}
There are two advantages to this. First, you no longer need to count
characters when extracting the date components. Second, you have a
little more freedom in defining your date format. For example, you
could use the following definition for oDateReg to also accept
single-digit months and/or days:
boost::regex oDateReg( "(\\d{1,2})-(\\d{1,2})-(\\d{4})" );
Andrew Holden
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net