c++ - Why am I not Able to Construct This Regex -


i wrote regex:

(.+?)\s*{?\s*(.+?;)\s*}?\s* 

which tests fine: https://regex101.com/r/gd2en7/1

but when try construct in c++ runtime-error.

unhandled exception @ 0x7714c52f in temp2.exe: microsoft c++ exception:
std::regex_error @ memory location 0x003bf2ec.

const auto input = "if (knr)\n\tfoo();\nif (spaces) {\n    foo();\n}\nif (allman)\n{\n\tfoo();\n}\nif (horstmann)\n{\tfoo();\n}\nif (pico)\n{\tfoo(); }\nif (whitesmiths)\n\t{\n\tfoo();\n\t}"s;  cout << input << endl;  cout << regex_replace(input, regex("(.+?)\\s*{?\\s*(.+?;)\\s*}?\\s*"), "$1 {\n\t$2\n}\n") << endl; 

live example

am using functionality c++ doesn't support?

you need escape curly braces. see std::regex ecmascript flavor reference:

\character
character character is, without interpreting special meaning within regex expression. character can escaped except form of special character sequences above.
needed for: ^ $ \ . * + ? ( ) [ ] { } |

regex_replace(input, regex("(.+?)\\s*\\{?\\s*(.+?;)\\s*\\}?\\s*"), "$1 {\n\t$2\n}\n") 

here ideone demo

#include <iostream> #include <regex> #include <string>  using namespace std;  int main() {     const auto input = "if (knr)\n\tfoo();\nif (spaces) {\n    foo();\n}\nif (allman)\n{\n\tfoo();\n}\nif (horstmann)\n{\tfoo();\n}\nif (pico)\n{\tfoo(); }\nif (whitesmiths)\n\t{\n\tfoo();\n\t}"s;      cout << regex_replace(input, regex("(.+?)\\s*\\{?\\s*(.+?;)\\s*\\}?\\s*"), "$1 {\n\t$2\n}\n") << endl;     //                                           ^^                ^^ } 

Comments