正则表达式捕获会使代码崩溃

Regexp capturing crashes the code

本文关键字:代码 崩溃 正则表达式      更新时间:2023-10-16

我试图弄清楚 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;
}
}
}

以下是结果:

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

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

第一个

大写\.caps\[0\]\.主格式\[0\]\.视频\。比特率选项 =

返回两个匹配项,因为std::cin >> needle;仅在找到第一个空格字符(第一个匹配项)之前读取。然后它读取下一个"单词"=,给出第二个匹配。


类似的行为发生在下一个

(大写字母\.caps\[0\]\.主格式\[0\]\.视频\。比特率选项 =)

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

在抛出 'std::regex_error'what
() 的实例后调用终止:regex_error


如果您想要整行,请改用std::getline

while (std::getline(std::cin, needle)) {
// ...
}

我无法在最后一个中止中重现任何中止

caps.caps\[0]

这将按预期返回匹配项。