2

我正在使用 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."

有趣/恼人的是,这似乎不会发生在具有相同测试数据的测试程序中。关于为什么会发生这种情况和/或如何解决它的任何想法?

4

1 回答 1

2

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

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

于 2011-02-11T18:27:53.483 回答