Combining two regular expression c++0x
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.
std::regex reg1("(\\d{4})-(\\d{2})-(\\d{2})|(\\d{2})/(\\d{2})/(\\d{4})");
std::smatch match;
if(std::regex_search(item, match, reg1)) {
std::cout << "Year=" << atoi(match.format("$1$6").c_str()) << std::endl;
std::cout << "Month=" << atoi(match.format("$2$5").c_str()) << std::endl;
std::cout << "Day=" << atoi(match.format("$3$4").c_str()) << std::endl;
}
(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.)
精彩评论