c++ - Boost 正则表达式抛出复杂性异常,而 std::regex 则不会

标签 c++ regex macos boost boost-regex

我遇到了一个奇怪的问题 - 我使用的库使用正则表达式,它可以是 booststd,具体取决于配置期间提供的选项。由于其他原因,我不能在我的代码中使用 std::regex 而是使用 boost 。当我开始调用内部使用正则表达式的库函数时,我的代码被阻塞了。经过几个小时的调试,我找到了它。简而言之,这段代码块:

std::string str = "/a/b/c/d/e/KEY/h/dsk-1474591592/ID-CERT";
std::string pattern = "^((?:(?!/KEY)(?:/.*)*)*)/KEY((?:/.+?)*)/ksk-.+/ID-CERT";
boost::regex re = regex(pattern);
boost::sregex_iterator iterator = boost::sregex_iterator(str.begin(), str.end(), re);

当我用这段代码编写一个小测试程序时,出现异常:

libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<std::runtime_error> >: The complexity of matching the regular expression exceeded predefined bounds.  Try refactoring the regular expression to make each choice made by the state machine unambiguous.  This exception is thrown to prevent "eternal" matches that take an indefinite period time to locate.
Abort trap: 6

相同的代码,如果改用 std::regex 则不会抛出。

我尝试了几个 boost 版本 - 1.54、1.58、1.59 - 都可以。我需要为此找到一个解决方法——要么禁止从 boost 中抛出这个确切的异常(这可能很危险),要么使正则表达式更简单(首选)。不幸的是,我对正则表达式没有太多经验,非常感谢任何有关如何使其更简单的建议!

更新(附加信息):

上面提到的正则表达式是如何创建的:它是由 library 处理的结果正则表达式.它使用 NDN-regex在这个function并通过这个 sanitizing function .

最佳答案

boost::regex(和 std::regex)在判断表达式太复杂时会抛出异常。有关 error_complexity 和相关 error_stack 的描述,请参见标准中的 [re.err]。

error_complexity The complexity of an attempted match against a regular expression exceeded a pre-set level.

它是如何决定的,以及什么是“太复杂”是实现定义的。

因此,您所看到的是“非常好”,但这对您来说并不是真正有用的答案。

关于c++ - Boost 正则表达式抛出复杂性异常,而 std::regex 则不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39712992/

相关文章:

macos - 无法在 mac 上为 csipsimple 配置被子

c++ - 如何找到当前专注于 macos 的程序?

php - 正则表达式将 <img> 相对 URL 更改为绝对

macos - Boot2docker 虚拟机图形

regex - 如何用单个空格替换换行符/换行符,但前提是它们在开始/结束正则表达式中?

python - 正则表达式和 grep 异常匹配

cocoa - 在 Cocoa View 中绘制居中对齐的文本

c++ - 我如何在 0(1) 操作中将 c++ vector 转换为 lisp vector

c++ - 从另一个 Nan::ObjectWrap 返回一个 Nan::ObjectWrap

c++ - 具有不同大小的二维结构数组成员变量