在抛出 'std::regex_error' 的实例后调用终止 what(): 括号未关闭

terminate called after throwing an instance of 'std::regex_error' what(): Parenthesis is not closed

本文关键字:终止 what 调用 std regex 实例 error      更新时间:2023-10-16

我会将代码中第一个g到第一个括号的字符串匹配。我不知道为什么不这样做,因为我使用了转义字符。 例如,在此字符串上:

你好测试g55_2( CNN

我打算匹配g55_2 g++ 5.4.0

#include <iostream>
#include<regex>
#include<string>
int main()
{
std::string s("g.*(");
std::regex re(s);
}

我 https://regex101.com/在这里尝试了我的正则表达式,它起作用了,但由于标题中的错误,我的 c++ 无法编译。

您在C++中逃脱了括号。正则表达式需要一个 \ 字符(需要在 C++ 中转义)和一个 ( 字符:

std::string s("g.*\(");

或者,使用原始字符串文本来避免担心C++逃避妨碍您的行为:

std::string s(R"(g.*()");

R"(...)"中的文字文本被视为字符串。

另请注意,*是贪婪的,但您希望它不贪婪,因此它停在第一个括号而不是最后一个括号。您可以添加一个?以使其不贪婪:

std::string s(R"(g.*?()");
相关文章: