为什么这个 C++11 std::regex 示例会抛出 regex_error 异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15671536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:37:46  来源:igfitidea点击:

Why does this C++11 std::regex example throw a regex_error exception?

c++regexc++11g++

提问by Stéphane

Trying to learn how to use the new std::regex in C++11. But the example I tried is throwing a regex_error exception I don't understand. Here is my sample code:

尝试学习如何在 C++11 中使用新的 std::regex。但是我试过的例子是抛出一个我不明白的 regex_error 异常。这是我的示例代码:

#include <iostream>
#include <regex>

int main()
{
    std::string str = "xyzabc1xyzabc2xyzabc3abc4xyz";
    std::regex re( "(abc[1234])" ); // <-- this line throws a C++ exception

    // also tried to do this:
    // std::regex re( "(abc[1234])", std::regex::optimize | std::regex::extended );

    while ( true )
    {
        std::cout << "searching in " << str << std::endl;
        std::smatch match;
        std::regex_search( str, match, re );
        if ( match.empty() )
        {
            std::cout << "...no more matches" << std::endl;
            break;
        }
        for ( auto x : match )
        {
            std::cout << "found: " << x << std::endl;
        }
        str = match.suffix().str();
    }
    return 0;
}

I compile and run like this:

我编译和运行是这样的:

g++ -g -std=c++11 test.cpp
./a.out
terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error

Looking at the backtrace in gdb, I see the exception thrown is regex_constants::error_brack.

查看 gdb 中的回溯,我看到抛出的异常是regex_constants::error_brack.

采纳答案by Stéphane

Thanks for the hint. Had no idea the regex code in g++ was incomplete.

谢谢你的提示。不知道 g++ 中的正则表达式代码不完整。

In the meantime, guess we'll have to refer to this old StackOverflow question:

与此同时,猜测我们将不得不参考这个旧的 StackOverflow 问题:

C++: what regex library should I use?

C++:我应该使用什么正则表达式库?