boost :: find_format_all,boost :: regex_finder和自定义正则表达式格式化程序的问题(bug boost 1.42)

时间:2010-05-26 15:26:17

标签: c++ boost boost-regex

我的代码已经运行了近4年(自1.33提升),今天我从1.36提升到1.42,现在我遇到了问题。

我在字符串上调用自定义格式化程序,以格式化与REGEX匹配的字符串部分。

例如,如果REGEX包含“([;:])”

,则字符串如:“abc; def:”将更改为“abc \ 2Cdef \ 3B”
boost::find_format_all( mystring, boost::regex_finder( REGEX ), custom_formatter() );

自定义格式化程序如下所示:

struct custom_formatter()
{

  template< typename T >
  std::string operator()( const T & s ) const
  {
      std::string matchStr = s.match_results().str(1);

      // perform substitutions

      return matchStr;
  }

}

这个工作正常,但有了1.42我知道有“非初始化”的s.match_results()会产生boost :: exception_detail :: clone_implINS0 _ :: error_info_injectorISt11logic_errorEEEE - 尝试访问未初始化的boost :: match_results&lt;&gt;类。

这意味着有时候我会在函数中格式化字符串,但没有匹配。

我做错了吗?或者在没有匹配时输入仿函数是正常的,我应该检查一下吗?

现在我的解决方案是尝试{} catch(){}异常并且一切正常,但不知何故感觉不太好。

EDIT1

实际上我在每个字符串的末尾都有一个新的空匹配要解析。

EDIT2:受ablaeul启发的一个解决方案

  template< typename T >
  std::string operator()( const T & s ) const
  {

      if( s.begin() == s.end() ) return std::string();

      std::string matchStr = s.match_results().str(1);

      // perform substitutions

      return matchStr;
  }

EDIT3似乎是(至少)提升1.42

的错误

1 个答案:

答案 0 :(得分:2)

结构find_regexF似乎是罪魁祸首。如您所见,它返回一个未初始化match_results()的空结果。通过SO查看了以下解决方案:

struct custom_formatter()
{

  template< typename T >
  std::string operator()( const T & s ) const
  {
      std::string matchStr;
      for (typename T::const_iterator i = Match.begin();
             i != Match.end();
             i++) {
          // perform substitutions via *i
      }
      return matchStr;
  }

}

编辑:查看Boost uses the formatter这里的另一种解决方案:

template<typename InputIteratorT>
std::string operator()( 
    const regex_search_result<InputIteratorT>& Replace ) const
{
    if ( Replace.empty() )
    {
        return std::string();
    }
    else
    {
        std::string matchStr = s.match_results().str(1);
        // perform substitutions
        return matchStr;      
    }
}