test11 test11 - 1 year ago 86
C++ Question

unchecked exception while running regex simple app

I have this simple program

string str = "D:\Praxisphase 1 project\test\Brainstorming.docx";
regex ex("[^\\]+(?=\.docx$)");
if (regex_match(str, ex)){
cout << "match found"<< endl;

expecting the result to be true, my regex is working since I have tried it online, but when trying to run in C++ , the app throws unchecked exception.

Answer Source

First of all, use raw string literals when defining regex to avoid issues with backslashes (the \. is not a valid escape sequence, you need "\\." or R"(\.)"). Second, regex_match requires a full string match, thus, use regex_search.

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

int main() {
    string str = R"(D:\Praxisphase 1 project\test\Brainstorming.docx)";
    // OR
    // string str = R"D:\\Praxisphase 1 project\\test\\Brainstorming.docx";
    regex ex(R"([^\\]+(?=\.docx$))");
    if (regex_search(str, ex)){
        cout << "match found"<< endl;
    return 0;

See the C++ demo

Note that R"([^\\]+(?=\.docx$))" = "[^\\\\]+(?=\\.docx$)", the \ in the first are literal backslashes (and you need two backslashes in a regex pattern to match a \ symbol), and in the second, the 4 backslashes are necessary to declare 2 literal backslashes that will match a single \ in the input text.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download