Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

regex

c++11

g++

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.

like image 616
Stéphane Avatar asked Mar 27 '13 23:03

Stéphane


People also ask

What is Regex_error?

std::regex_errorDefines the type of exception object thrown to report errors in the regular expressions library.

Why is std :: regex slow?

The current std::regex design and implementation are slow, mostly because the RE pattern is parsed and compiled at runtime. Users often don't need a runtime RE parser engine as the pattern is known during compilation in many common use cases.


1 Answers

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?

like image 93
Stéphane Avatar answered Oct 11 '22 18:10

Stéphane