Jon*_*Mee 4 c++ regex runtime-error construct c++11
我写了这个正则表达式:
(.+?)\s*{?\s*(.+?;)\s*}?\s*
Run Code Online (Sandbox Code Playgroud)
哪个测试正常:https : //regex101.com/r/gD2eN7/1
但是当我尝试用 C++ 构建它时,我得到了一个运行时错误。
temp2.exe 中 0x7714C52F 处的未处理异常:Microsoft C++ 异常:
内存位置 0x003BF2EC 处的 std::regex_error。
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;
Run Code Online (Sandbox Code Playgroud)
我是否使用了 C++ 不支持的功能?
你需要逃避花括号。请参阅std::regexECMAScript 风格参考:
\character
该字符的字符,因为它是,没有一个正则表达式表达式中解释它的特殊含义。除了构成上述任何特殊字符序列的字符外,任何字符都可以转义。
需要:^$\.*+?()[]{}|
regex_replace(input, regex("(.+?)\\s*\\{?\\s*(.+?;)\\s*\\}?\\s*"), "$1 {\n\t$2\n}\n")
Run Code Online (Sandbox Code Playgroud)
这是一个IDEONE演示
#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;
// ^^ ^^
}
Run Code Online (Sandbox Code Playgroud)