16

您好,我是正则表达式的新手,根据我从 c++ 参考网站了解的内容,可以获得匹配结果。

我的问题是:如何检索这些结果?smatch和 和有什么不一样cmatch?例如,我有一个由日期和时间组成的字符串,这是我写的正则表达式:

"(1[0-2]|0?[1-9])([:][0-5][0-9])?(am|pm)"

现在,当我regex_search对字符串和上面的表达式执行 a 时,我可以找到字符串中是否有时间。但我想将那个时间存储在一个结构中,这样我就可以分开小时和分钟。我正在使用 Visual Studio 2010 C++。

4

2 回答 2

22

如果你使用 egstd::regex_search那么它会填写一个std::match_result你可以使用的地方operator[]来获取匹配的字符串。

编辑:示例程序:

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

void test_regex_search(const std::string& input)
{
    std::regex rgx("((1[0-2])|(0?[1-9])):([0-5][0-9])((am)|(pm))");
    std::smatch match;

    if (std::regex_search(input.begin(), input.end(), match, rgx))
    {
        std::cout << "Match\n";

        //for (auto m : match)
        //  std::cout << "  submatch " << m << '\n';

        std::cout << "match[1] = " << match[1] << '\n';
        std::cout << "match[4] = " << match[4] << '\n';
        std::cout << "match[5] = " << match[5] << '\n';
    }
    else
        std::cout << "No match\n";
}

int main()
{
    const std::string time1 = "9:45pm";
    const std::string time2 = "11:53am";

    test_regex_search(time1);
    test_regex_search(time2);
}

程序的输出:

匹配
匹配[1] = 9
匹配[4] = 45
匹配[5] = 下午
匹配
匹配[1] = 11
匹配[4] = 53
匹配[5] = 上午
于 2012-10-16T06:17:43.903 回答
1

只需使用命名组。

(?<hour>(1[0-2]|0?[1-9]))([:](?<minute>[0-5][0-9]))?(am|pm)

好的,vs2010 不支持命名组。您已经在使用未命名的捕获组。通过他们。

于 2012-10-16T06:17:44.447 回答