正则表达式捕获会使代码崩溃
Regexp capturing crashes the code
我试图弄清楚 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]
这将按预期返回匹配项。
相关文章:
- C++代码崩溃并具有无限循环
- 为什么在同一条件变量上使用多个互斥锁会使此代码崩溃?
- 赋值运算符在我制作类模板时使代码崩溃
- 为什么这段代码崩溃了
- 正则表达式捕获会使代码崩溃
- 带有运算符的简单用户定义类 = 重载代码崩溃
- 使用自动循环时代码崩溃
- 当我输入12位数字时,为什么以下代码崩溃
- 为什么我的代码崩溃了,浮点异常
- PQXX简单代码崩溃了
- 试图通过struct时C 代码崩溃
- 当从共享库运行时,为什么此Android NDK代码崩溃
- 程序在Windows中的DLL边界上使用嵌入式Python/C 代码崩溃
- 对 NULL 值的按位操作是否会使C++中的代码崩溃
- C 程序用退出代码崩溃:9(Sigkill)
- 为什么以下代码崩溃
- 当未选择 /CLR时,编译的MATLAB代码崩溃
- C++Visual Studio Release生成未使用的代码崩溃
- 在RELEASE配置中使用向量push_back时,C++代码崩溃
- RCPP代码崩溃