提升regex_replace异常:“...抛出此异常以防止”永恒“匹配......”偶尔会抛出

时间:2011-02-11 15:32:06

标签: c++ regex boost boost-regex

我正在使用Boost.Regex(boost-1.42)删除多行字符串的第一行(一个包含多行以'\ n'结尾的相当大的字符串)。

即。使用regex_replace做类似于s /(。*?)\ n //

的操作
  string
  foo::erase_first_line(const std::string & input) const
  {
    static const regex line_expression("(.*?)\n");
    string  empty_string;

    return boost::regex_replace(input,
                                line_expression,
                                empty_string,
                                boost::format_first_only);
  }

此代码抛出以下异常:

"terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<std::runtime_error> >'
  what():  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."

有趣/令人讨厌的是,在具有相同测试数据的测试程序中似乎没有发生这种情况。有关为什么会发生这种情况和/或如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:2)

尝试在正则表达式的开头放置一个“字符串的开头”标记(默认的Perl兼容模式中的“\ A”),以使其更明确,您希望它只匹配第一行。

如果没有明确地将开头与字符串匹配,看起来boost正在应用其“最左边最长”的规则,这就是造成这种情况的原因:http://www.boost.org/doc/libs/1_45_0/libs/regex/doc/html/boost_regex/syntax/leftmost_longest_rule.html

相关问题