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());
}
to combine two expressions or more, put every expression in brackets, and use: *?
\$ will help to find the character "$" available in the content based on the expression flags assigned to the regular expression. Say for example: \$: only find the single "$" in a content \$/g: find the "$" globally available in content.
Concatenation: If R1 and R2 are regular expressions, then R1R2 (also written as R1. R2) is also a regular expression. L(R1R2) = L(R1) concatenated with L(R2). Kleene closure: If R1 is a regular expression, then R1* (the Kleene closure of R1) is also a regular expression.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With