I wrote this regex:
(.+?)\s*{?\s*(.+?;)\s*}?\s*
Which tests fine: https://regex101.com/r/gD2eN7/1
But when I try to construct it in C++ I get a runtime-error.
Unhandled exception at 0x7714C52F in temp2.exe: Microsoft C++ exception:
std::regex_error at 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;
Am I using functionality that C++ doesn't support?
You need to escape the curly braces. See the std::regex
ECMAScript flavor reference:
\character
The character character as it is, without interpreting its special meaning within a regex expression. Any character can be escaped except those which form any of the special character sequences above.
Needed for:^
$
\
.
*
+
?
(
)
[
]
{
}
|
regex_replace(input, regex("(.+?)\\s*\\{?\\s*(.+?;)\\s*\\}?\\s*"), "$1 {\n\t$2\n}\n")
Here is an 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;
// ^^ ^^
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments