2011-03-15 128 views
0

我試圖在一行中用'$'對分隔的一些字符串之間循環,用一個特定的值替換每個匹配,以便獲得所有標記替換的輸出行,但是我停留在第二場比賽,因爲我不知道如何連接新的替換值:regex_search and regex_replace with Boost

const boost::regex expression("\\$[\\w]+\\$"); 
string fileLine("Mr $SURNAME$ from $LOCATION$"); 
string outLine; 

string::const_iterator begin = fileLine.begin(); 
string::const_iterator end = fileLine.end(); 

boost::match_results<string::const_iterator> what; 
boost::match_flag_type flags = boost::match_default; 

while (regex_search(begin, end, what, expression, flags)) { 
    actualValue = valuesMap[what[0]]; 

    ostringstream t(ios::out | ios::binary); 
    ostream_iterator<char, char> oi(t); 

    boost::regex_replace(oi, begin, end, expression, actualValue, 
         boost::match_default | boost::format_first_only); 
    outLine.append(t.str()); 
    begin = what[0].second; 
} 

的問題是在outLine.append(t.str())作爲連接不正確,因爲後第一場比賽,outline拿着下一場比賽之前的一些角色。

回答

0

自從你在字符串只請求第一個值被替換(通過使用升壓:: format_first_only標誌)原始字符串

"Mr $SURNAME$ from $LOCATION$" 

將在第一次迭代轉換成

"Mr ACTUAL_VAL from $LOCATION$" 

然後

" from ACTUAL_VAL" 

將被附加到它,因爲你明確地設置開始「什麼[0]。秒。 所以最終輸出是

"Mr ACTUAL_VAL from $LOCATION$ from ACTUAL_VAL" 

這是不是你所需要的。 有副作用,在這裏工作的例子 - 它修改fileLine:

const boost::regex expression("\\$[\\w]+\\$"); 
    string fileLine("Mr $SURNAME$ from $LOCATION$"); 
    string outLine; 

    string::const_iterator begin = fileLine.begin(); 
    string::const_iterator end = fileLine.end(); 

    boost::match_results<string::const_iterator> what; 
    boost::match_flag_type flags = boost::match_default; 

    while (regex_search(begin, end, what, expression, flags)) 
    { 
     const char* actualValue = valuesMap[what[0]]; 

     ostringstream t(ios::out | ios::binary); 
     ostream_iterator<char, char> oi(t); 

     boost::regex_replace(oi, begin, end, expression, 
`enter code here`actualValue, boost::match_default | boost::format_first_only); 

     fileLine.assign(t.str()); 
     begin = fileLine.begin(); 
     end = fileLine.end();   
    } 

    std::cout << fileLine << std::endl; 

如果你不想修改fileLine,那麼你就應該讓「開始」和「結束」,以紀念滑動的開始和結束窗口只包含一個模式。

0

雖然我不是100%地肯定你的意圖,我相信你的目標是具有valuesMap相應值替換 每個匹配的子字符串在fileLine
如果是的話,下面的代碼可能會滿足你的目的:

...same as your code... 

    while (regex_search(begin, end, what, expression, flags)) { 
    outLine.insert(outLine.end(), begin, what[0].first); 
    outLine += valuesMap[what[0]]; 
    begin = what[0].second; 
    } 

    outLine.insert(outLine.end(), begin, end); 

希望這有助於