mardi 18 juin 2019

why this regex throwing an instance of 'std::regex_error' and generate coredump? [duplicate]

This question already has an answer here:

I'am studying c++ regex. below code can pass g++ 4.8.5 compile, but when I run it, program throw exception and core dump:

$ ./17.3
terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted (core dumped)

gdb show that the line 12:regex r(pattern, regex_constants::ECMAScript);.

I put my code to http://cpp.sh/, the code can run correctly and get correct result.

is that my compiler is too old? but other programs used regex compiled by g++ 4.8.5 can run correctly, could anyone tell me why? thanks a lot.

#include <regex>                                                                                    
#include <string>                                                                                   
#include <iostream>                                                                                 

using namespace std;                                                                                

int main()                                                                                          
{                                                                                                   
    string pattern("[^c]ei");                                                                       
    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";                                                                                                                                                                                                                                   

    regex r(pattern, regex_constants::ECMAScript);                                                  
    smatch results;                                                                                 

    string test_str = "receipt freind theif receive";                                               

    try {                                                                                           
        if (regex_search(test_str, results, r)) {                                                   
            cout << results.str() << endl;                                                          
        }                                                                                           
    } catch (regex_error e) {                                                                       
        cout << e.what() << "\ncode: " << e.code() << endl;                                         
    }                                                                                               
} 

Aucun commentaire:

Enregistrer un commentaire