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

Why does this C++11 std::regex example throw a regex_error exception?(为什么这个 C++11 std::regex 示例会引发 regex_error 异常?)

本文介绍了为什么这个 C++11 std::regex 示例会引发 regex_error 异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

#include <iostream>#include <正则表达式>主函数(){std::string str = "xyzabc1xyzabc2xyzabc3abc4xyz";std::regex re("(abc[1234])");//<-- 此行抛出 C++ 异常//也尝试过这样做://std::regex re( "(abc[1234])", std::regex::optimize | std::regex::extended );而(真){std::cout <<"搜索" <

我是这样编译和运行的:

g++ -g -std=c++11 test.cpp./a.out在抛出 'std::regex_error' 的实例后调用终止什么():正则表达式错误

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

解决方案

感谢您的提示.不知道 g++ 中的正则表达式代码不完整.

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

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

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:

#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.

解决方案

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

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

C++: what regex library should I use?

这篇关于为什么这个 C++11 std::regex 示例会引发 regex_error 异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么这个 C++11 std::regex 示例会引发 regex_error 异常?

基础教程推荐