简体   繁体   English

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

[英]C++ regex_search capture retrieval fails at runtime

I'm following an example in Stroustrup's Tour of C++ - section 7.3.1 (page 79). 我正在遵循Stroustrup的C ++之旅-7.3.1节(第79页)中的示例。 This code compiles on VS 2013 Update 3 but fails at runtime: 该代码在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;
    }
}

Any idea what is going on? 知道发生了什么吗? It fails on matches[1] where I'm trying to output the capture group result to stdout. 我尝试将捕获组结果输出到stdout的matchs matches[1]上失败。 The runtime assertion I see is "string iterators incompatible". 我看到的运行时断言是“字符串迭代器不兼容”。

smatch object contains iterators into the string you searched with the regular expression. smatch对象将迭代器包含到使用正则表达式搜索的字符串中。 Said string is a temporary in your example, and is dead by the time you are trying to inspect the matches. 在您的示例中,该字符串是临时字符串,在您尝试检查匹配项时该字符串已消失。 All those iterators are dangling. 所有这些迭代器都悬而未决。

Make it 做了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM