I have a text where a date can look like this: 2011-02-02 or like this: 02/02/2011, this is what I have been written so far, and my question is, if there is a nice way of combining these two regular expressions into one?
std::regex reg1("(\\d{4})-(\\d{2})-(\\d{2})");
std::regex reg2("(\\d{2})/(\\d{2})/(\\d{4})");
smatch match;
if(std::regex_search(item, match, reg1))
{
Date.wYear = atoi(match[1].str().c_str());
Date.wMonth = atoi(match[2].str().c_str());
Date.wDay = atoi(match[3].str().c_str());
}
else if(std::regex_search(item, match, reg2))
{
Date.wYear = atoi(match[3].str().c_str());
Date.wMonth = atoi(match[2].str().c_str());
Date.wDay = atoi(match[1].str().c_str());
}
You could combine the two regexes together by
|. Since only one of the|can be matched, we can then concatenate capture groups of different parts and think them as a whole.(Unfortunately C++0x’s regex does not support named capture group, otherwise I’d suggest loop over an array of regexes using named capture instead.)