组合两个正则表达式c++0x

Combining two regular expression c++0x

本文关键字:两个 正则表达式 c++0x 组合      更新时间:2023-10-16

我有一个文本,其中日期可以看起来像这样:2011-02-02或这样:02/02/2011,这是我到目前为止所写的,我的问题是,如果有一个很好的方法将这两个正则表达式组合成一个?

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());
}

您可以通过|将两个正则组合在一起。由于只有一个|可以匹配,因此我们可以将不同部分的捕获组连接起来,并将它们视为一个整体。

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;
} 

(不幸的是c++ 0x的正则表达式不支持命名捕获组,否则我建议使用命名捕获来循环遍历正则表达式数组)