C ++的正则表达式是否具体?

时间:2013-02-04 15:18:22

标签: c++ regex c++11

我很遗憾这类似于家庭作业。但是,我刚才无法使用std :: regex解析数天,数月和数年。我只是看不出有什么遗漏。

#include<iostream>
#include<string>
#include<vector>
#include<regex>

int main()
{
    std::vector<std::string> series;
    series.push_back("2013-02-01,54.87,55.20,54.67,54.92,2347600,54.92");
    series.push_back("2013-01-31,54.74,54.97,53.99,54.29,3343300,54.29");
    series.push_back("2013-01-30,54.84,55.35,54.68,54.68,2472800,54.68");

    const std::regex date("(\\d{4})-(\\d{2})-(\\d{2})");
    std::smatch dates;

    for (unsigned int  i = 0; i < series.size() ; i++)
    {
        if (std::regex_match(series[i], dates, date))
            std::cout << dates[1] << "\t" << dates[2] << "\t" << dates[3] << std::endl;
        else
            std::cout << "No match!" << std::endl;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:4)

为此,请使用regex_search,而不是regex_matchregex_match要求正则表达式与整个目标文本匹配; regex_search找到目标文本的任何部分匹配。或者您可以将正则表达式更改为以“。*”结尾以吞下目标文本的其余部分。