使用 MSVC 2013 的正则表达式错误

Regex error using MSVC 2013

我有一段 xml 类似的代码要解析,使用 MSVC 2013 中的 std::regex

<GLVertex>
#version 450 core
layout(location = 0) in vec3 pos;
in VertexInfo{
    vec2 uv;
}vertexInfo;
void main(){
    gl_Position = vec4(pos, 1.0);
    vertexInfo.uv = pos.xy;
}
<GLVertex/>
<GLFragment>
#version 450 core
layout(location = 0) uniform sampler2D g_map;
uniform Color {
    vec4 color;
};
layout(location = 0) out vec4 fragColor;
void main(){
    fragColor = texture(g_map, vertexInfo.uv);
}
<GLFragment/>

这是模式:

<GLVertex>((.|\n)+)<GLVertex\/>

但是程序总是崩溃!我的正则表达式中有错误吗?我在 regex101 上测试过。

PS。当我删除第 5 行时:

vec2 uv;

一切正常!

您得到一个 Stack overflow (parameters: 0x00000001, 0x00312FFC) 异常,因为该模式效率不高。我认为这与 std::regex 处理重复组的方式有关(您定义了一个带有 +-量词组 (.|\n)+ 的组)。此模式匹配每个不是换行符 (.) 或换行符 (\n) 的字符,然后将匹配项存储在缓冲区中。然后,迭代器调试问题 仅在 调试 模式 中发生。其中std::_Orphan_Me是break发生的地方,在匹配字符串时被认为是最"expensive"的方法。参见 performance killer -Debug Iterator Support in Visual studio

您应该切换到 Release 模式,或者使用不需要使用重复组的正则表达式进行测试,例如 any non-null带有惰性量词 *?:

的字符 [^\x00]
std::string str1 = "<GLVertex>\n#version 450 core\nlayout(location = 0) in vec3 pos;\nin VertexInfo{\n    vec2 uv;\n}vertexInfo;\nvoid main(){\n    gl_Position = vec4(pos, 1.0);\n    vertexInfo.uv = pos.xy;\n}\n<GLVertex/>\n<GLFragment>\n#version 450 core\nlayout(location = 0) uniform sampler2D g_map;\nuniform Color {\n    vec4 color;\n};\nlayout(location = 0) out vec4 fragColor;\nvoid main(){\n    fragColor = texture(g_map, vertexInfo.uv);\n}\n<GLFragment/>"; 
std::regex reg1("<GLVertex>([^\x00]*?)<GLVertex/>");
std::smatch find1;
if (std::regex_search(str1, find1, reg1)){
    std::cout << find1[1].str();
}