-1

I dont understand exactly how the escaping with regex word. I try to detect a "+". I know it is also a special sign of regex to indicate that there follows one ore more signs.

From my understanding these special signs need to be escaped with "\". For + this seems to work with "." If i however escape a plus with "+ i get a runtime exception.

"matched. regex_error(error_badrepeat): One of *?+{ was not preceded by a valid reguar expression."

So I assume it is not correctly escaped.

Example:

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



int main() 
try {
    std::regex point("\.");

    std::string s1 = ".";
    if (std::regex_match(s1, point))
        std::cout << "matched" << s1;

    std::regex plus("\+");

    std::string s2 = "+";
    if (std::regex_match(s2, plus))
        std::cout << "matched" << s2;

    char c;
    std::cin >> c;

}
catch (std::runtime_error& e) {
    std::cerr << e.what()<<'\n';

    char c;
    std::cin >> c;
}
catch (...) {
    std::cerr << "unknown error\n";

    char c;
    std::cin >> c;
}
aek8
  • 319
  • 1
  • 8
  • 22
Sandro4912
  • 313
  • 1
  • 9
  • 29

2 Answers2

1

You are using a C++ string literal, where \ is a special character, and should be escaped. So you should use "\\+".

To avoid double escaping, you can also use raw string literal, e.g. R"(\+)".

xskxzr
  • 12,442
  • 12
  • 37
  • 77
0

DOT ., plus sign + are special characters for regex operation in C++. So you have to do it like below:-

    regex point("\\.");
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17