C ++ regex_search捕获检索在运行时失败

时间:2014-08-05 04:41:30

标签: c++ regex search match

我在Stroustrup的C ++之旅中有一个例子 - 第7.3.1节(第79页)。此代码在VS 2013 Update 3上编译,但在运行时失败:

regex pat {R"(\w{2}\s+(\d{5}))"};
smatch matches;
if (regex_search(string{"CA 90210"}, matches, pat))
{
    if ((matches.size() > 1) && matches[1].matched)
    {
        cout << matches[1] << endl;
    }
}

知道发生了什么事吗?它在matches[1]上失败,我试图将捕获组结果输出到stdout。我看到的运行时断言是“字符串迭代器不兼容”。

1 个答案:

答案 0 :(得分:4)

smatch对象包含使用正则表达式搜索的字符串中的迭代器。在您的示例中,所述字符串是临时的,并且在您尝试检查匹配时已经死了。所有这些迭代器都在悬空。

成功

string s = "CA 90210";
if (regex_search(s, matches, pat)) {...}