我有一个文本,其中的日期看起来可能像这样: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的正则表达式不支持命名捕获组,否则,我建议使用命名捕获在一组正则表达式上循环。)

关于c++ - 组合两个正则表达式C++ 0x,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5815416/

10-12 12:30
查看更多