【发布时间】:2017-08-12 02:04:20
【问题描述】:
我正在使用 VS2015 社区,为什么下面的代码在我的计算机上以特定长度的字符串抛出 std::regex_error。
#include <string>
#include <regex>
#include <iostream>
int main()
{
try {
std::string subject(497, '-');
std::regex pattern("(.)+");
bool match = std::regex_search(subject, pattern);
std::cout << std::boolalpha << match << std::endl;
}
catch(const std::regex_error& e) {
std::cerr << "1: " << e.what() << std::endl;
}
try {
std::string subject(498, '-');
std::regex pattern("(.)+");
bool match = std::regex_search(subject, pattern);
std::cout << std::boolalpha << match << std::endl;
}
catch(const std::regex_error& e) {
std::cerr << "2: " << e.what() << std::endl;
}
}
输出是:
true
2: regex_error(error_stack): There was insufficient memory to determine whether the regular expression could match the specified character sequence.
谢谢。
【问题讨论】:
-
也许你的正则表达式太模棱两可了。你应该尝试使用
"[-]+" -
@LingboTang 括号中的单个破折号是什么意思?
-
这意味着你应该只捕获字符
"-" -
@alfC 这是真的。在此之前,我不知道 regex_search 会抛出异常。谢谢
-
@LingboTang 这不是我想要的。默认情况下,
std::regex使用 ECMAScript 语法,我想匹配包含任何字符的字符串(包括\r)但\n在\n分隔的主题中,所以我这样写:((.|\r)*)\n,然后它会崩溃,但不是每次都崩溃。