Regexp捕获使代码崩溃 我想弄清楚C++中的正则表达式是如何工作的,所以我在这个例子中尝试了不同的正则表达式,看看它们是否匹配: #include <regex> int main(){ while (true) { string needle; cin >> needle; regex regexp(needle); std::smatch smatch; string haystack = "caps.caps[0].MainFormat[0].Video.BitRateOptions = 896, 1536"; bool match = regex_search(haystack, smatch, regexp); if (match) { cout << "Matched" << endl; } else { cout << "Mismatch" << endl; } } }

Regexp捕获使代码崩溃 我想弄清楚C++中的正则表达式是如何工作的,所以我在这个例子中尝试了不同的正则表达式,看看它们是否匹配: #include <regex> int main(){ while (true) { string needle; cin >> needle; regex regexp(needle); std::smatch smatch; string haystack = "caps.caps[0].MainFormat[0].Video.BitRateOptions = 896, 1536"; bool match = regex_search(haystack, smatch, regexp); if (match) { cout << "Matched" << endl; } else { cout << "Mismatch" << endl; } } },c++,regex,C++,Regex,为什么caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions=返回两个匹配项,为什么捕获此正则表达式会使代码崩溃?基于此,我假设当我想要匹配'['或']'时,我需要对其进行转义,可能还有一些其他情况下,错误构造的regexp可能会使进程崩溃。是否有任何选项可以处理未替换的“[”或“]”和其他错误的regexp,这样代码就不会崩溃,而是不匹配?我正在Windows 10上使用Visual Studio 2017。谢谢第一个 caps\.cap

为什么
caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions=
返回两个匹配项,为什么捕获此正则表达式会使代码崩溃?基于此,我假设当我想要匹配'['或']'时,我需要对其进行转义,可能还有一些其他情况下,错误构造的regexp可能会使进程崩溃。是否有任何选项可以处理未替换的“[”或“]”和其他错误的regexp,这样代码就不会崩溃,而是不匹配?我正在Windows 10上使用Visual Studio 2017。谢谢第一个

caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions=

返回两个匹配项,因为只有在找到第一个空格字符(第一个匹配项)后才会读取。然后它读取下一个“单词”
=
,这将给出第二个匹配项


下一个也会发生类似的行为

(caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions=)

第一部分读取
(…
,不包括第一个空格。现在正则表达式不完整,并引发异常。 对于g++来说,这看起来像

在抛出“std::regex_error”实例后终止调用
what():正则表达式错误


如果需要完整的行,请使用


我不能用最后一个复制任何中止

caps.caps\[0]


这是一个预期的匹配。

不看你的正则表达式,我认为这是不能回答的。我的正则表达式在最后一个代码片段中显示出来了。我尝试过各种正则表达式模式,其中一些代码崩溃了。你可能看到的是一个与VC++中的C++正则表达式相关的问题。释放模式。
caps.caps[0].MainFormat[0].Video.BitRateOptions
Mismatch
(caps.caps[0].MainFormat[0].Video.BitRateOptions)
Mismatch
caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions
Matched
(caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions)
Matched
caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions=
Mismatch
(caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions=)
Mismatch
caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions =
Matched
Matched
(caps\.caps\[0\]\.MainFormat\[0\]\.Video\.BitRateOptions =)
THIS ONE BREAK THE PROCESS AND ENDS
caps.caps\[0]
THIS ONE BREAK THE PROCESS AND ENDS
while (std::getline(std::cin, needle)) {
// ...
}