检索 C++ 中的正则表达式搜索

Retrieving a regex search in C++

本文关键字:正则表达式 搜索 C++ 检索      更新时间:2023-10-16

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

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

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

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

如果您使用 例如 std::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 << "Matchn";
        //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 matchn";
}
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] = 上午

只需使用命名组。

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

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