Home > Blockchain >  Why does following regex throws an exception
Why does following regex throws an exception

Time:09-23

The idea of application is to convert backslashes into forwardslashes. Running following code:

int main() {
    std::string x = "\\";
    std::string s = "C:\\tony\\hawk\\";
    std::cout << std::regex_replace(s,std::regex(x),"/") << std::endl;
    //std::cout << boost::regex_replace(s,boost::regex("\\\\"),"\\") << std::endl;
    std::cout << s << std::endl;
}

results in throwing this error message:

terminate called after throwing an instance of 'std::regex_error'
  what():  Unexpected end of regex when escaping.
fish: Job 1, './a.out' terminated by signal SIGABRT (Abort)

I cannot understand what is wrong with the "\\" regex. Shouldn't it match all of the backslashes?

CodePudding user response:

std::string x = "\\";

The above becomes a string with a single \, which isn't a valid regular expression. When creating strings with backslashes, it's convenient to use raw string literals. Example:

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

int main() {
    std::string x = R"aw(\\)aw";            // now two backslashes
    std::string s = R"aw(C:\tony\hawk\)aw"; // no need to escape the backslashes
    
    std::cout << std::regex_replace(s, std::regex(x),"/") << '\n';
    
    std::cout << s << '\n';
}

Output:

C:/tony/hawk/
C:\tony\hawk\
  • Related