2014-11-01 45 views
0

我想用regex_replace簡化的數學表達式跡象替換字符串,這裏是一個示例代碼:有條件使用boost :: regex_replace

string entry="6+-3++5"; 
boost::regex signs("[\-\+]+"); 
cout<<boost::regex_replace(entry,signs,"?")<<endl; 

的輸出是6 3 5?。我的問題是:如何用一些簡潔的正則表達式工具獲得6-3 + 5的正確結果?非常感謝。

試圖與sregex_iterator和SMATCH別的東西,但仍然有一些問題:

string s="63--17--42+5555"; 
collect_sign(s); 
Output is 
63+17--42+5555+42+5555+5555 
i.e. 
63+(17--42+5555)+(42+5555)+5555 

在我看來,這個問題是關係到match.suffix(),可能有人幫助嗎? collect_sign函數基本上只是迭代每個符號串,如果「 - 」的數字是奇數/偶數,則將其轉換爲「 - 」/「+」,然後將符號的後綴表達式拼接在一起。

void collect_sign(string& entry) 
{ 
    boost::regex signs("[\-\+]+"); 
    string output=""; 
    auto signs_begin = boost::sregex_iterator(entry.begin(), entry.end(), signs); 
    auto signs_end = boost::sregex_iterator(); 
    for (boost::sregex_iterator it = signs_begin; it != signs_end; ++it) 
    { 
     boost::smatch match = *it; 
     if (it ==signs_begin) 
      output+=match.prefix().str(); 
     string match_signs = match.str(); 
     int n_minus=count(match_signs.begin(),match_signs.end(),'-'); 
     if (n_minus%2==0) 
      output+="+"; 
     else 
      output+="-"; 
     output+=match.suffix(); 
    } 
    cout<<"simplify to: "<<output<<endl; 
} 

回答

0

用途:

[+\-*\/]*([+\-*\/]) 

替換:

$1 

您可以測試here

+0

對不起,這不適用於像6--3 ++ 5這樣的東西。預先感謝您提出任何進一步的建議。 – lychee10 2014-11-01 20:17:29

+0

在這種情況下,你不希望'6-3 + 5'結果?你可以看到結果[link](http://regex101.com/r/yR4cT9/4) – Croises 2014-11-01 20:20:18

+0

這是一個數學表達式,所以6--3 ++ 5應該是6 + 3 + 5。該規則基本上簡化爲 - 如果有奇數個 - 或否則。 – lychee10 2014-11-01 20:26:41

0

如果你只是想要一個數學上的簡潔,你可以使用:

s = boost::regex_replace(s, boost::regex("(?:++|--"), "+", boost::format_all); 
s = boost::regex_replace(s, boost::regex("(?:+-|-+"), "-", boost::format_all); 
+0

當然,但是有可能使它更一般嗎? Python控制檯可以處理6 +++ 3 - + - 5之類的東西。 – lychee10 2014-11-01 20:49:57

+0

我只是編輯代碼,現在試試它是否可以 – Croises 2014-11-01 21:10:20