为什么我无法构建此正则表达式

Why am I not Able to Construct This Regex

我写了这个正则表达式:

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

哪个测试正常:https://regex101.com/r/gD2eN7/1

但是当我尝试用 C++ 构建它时,出现运行时错误。

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*"), " {\n\t\n}\n") << endl;

Live Example

我是否使用了 C++ 不支持的功能?

你需要转义大括号。见 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*"), " {\n\t\n}\n")

这是一个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*"), " {\n\t\n}\n") << endl;
    //                                           ^^                ^^
}