Isura Nirmal Isura Nirmal - 19 days ago 6
C++ Question

Regex LookAround dont work in C++

I have a fairly good understanding about the Regex work in Python but the same regex string for lookaround work dont work in C++. I have tested this with following example, https://regex101.com/r/5ad2Cu/1 . This looks fine. However, same string shows false for the following C++ code fragment.

#include <iostream>
#include <regex>
using namespace std;
int main()
{
const char* rejectReason = "Failed to execute SQL. Error=ORA-00936: missing expression";
regex rgx(".+?(?=(ORA-([0-9]{5}):))");
cout<<regex_match(rejectReason, rgx)<<endl;
return 0;
}


I am somewhat new to C++ and many references shows that lookahead works but look after dont work in C++ and no mention about this lookaround. So isn't there any straight forward way to do this in C++?

Answer

Try this as starter, this will give you a basic idea how regex library works.

#include <iostream>
#include <regex>
using namespace std;

int main()
{
    string rejectReason = "Failed to execute SQL. Error=ORA-00936: missing expression";
    regex rgx(".*Error=ORA-([0-9]{5}).*$");
    if (regex_match(rejectReason, rgx)) {
        cout << "String matches" <<endl;
    }

    smatch match;
    string result;
    if (regex_search(rejectReason, match, rgx) && match.size() > 1) {
        result = match.str(1);
    } else {
        result = string("");
    }

    cout << result << endl;
    return 0;
}
Comments