2010-05-26 45 views
2

問題我有一段已經工作了近4年的代碼(自boost 1.33開始),今天我從boost 1.36升級到1.42現在我有一個問題。boost :: find_format_all,boost :: regex_finder和自定義正則表達式格式化(bug boost 1.42)

我正在調用一個字符串的自定義格式化程序來格式化與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(),它產生提振:: exception_detail :: clone_implINS0 _ :: error_info_injectorISt11logic_errorEEEE - 嘗試訪問uninitialzed boost :: match_results <> clas秒。

這意味着有時我在仿函數中格式化字符串,但沒有匹配。

我做錯了什麼?或者在沒有匹配的情況下進入函子是正常的,我應該檢查某些東西?

現在我的解決方案是嘗試{} 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

回答

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;  
    } 
} 
+0

這裏的問題是,你沒有正則表達式組。 * i上的每次迭代都會給你一個角色,但是你不能得到你想要的組(例如我認爲更復雜的正則表達式)。 但是我可以在開始時只測試s.begin()== s.end(),如果是這樣的話就退出。但我真的不明白爲什麼我會得到空的結果。 – Nikko 2010-05-26 16:51:41

+0

是的我已經做了這樣的事情,至少當我使用boost版本1.42,等待錯誤更正。謝謝您的幫助。 – Nikko 2010-05-29 16:41:25