2011-05-15 47 views
3

多重替換這是我的代碼如何做到使用boost ::正則表達式

// replace all new lines with string "nl" 
std::string s = "Stack\nover\rflowâ€"; 
boost::regex expr1("(\\n)|(\\r)"); 
std::string fmt("nl"); 
std::string s2 = boost::regex_replace(s, expr, fmt); 

然後用空字符串替換所有非ASCII字符

boost::regex expr2("([^\x20-\x7E])") 
std::string fmt2(""); 
std::cout << boost::regex_replace(s2, expr2, fmt2) << std::endl; 

我寧願有一個電話來代替,而不是兩個。

+0

我知道它不直接回答你的問題,但我認爲你應該留下兩個不同的電話,因爲這是兩個獨立的任務。 – MByD 2011-05-15 01:27:35

+0

下面的答案可以解決您的問題。如果您將其標記爲正確,那將會很好。 – Clocks 2014-03-12 16:13:19

回答

6

這將做到這一點:

std::string s = "Stack\nover\rflowâ€"; 
boost::regex expr("(\\n)|(\\r)|([^\x20-\x7E])"); 
std::string fmt("(?1nl)(?2nl)"); // Omitted the (?3) as a no-op 
std::string s2 = boost::regex_replace(s, expr, fmt, boost::match_default | boost::format_all); 
std::cout << s2 << std::endl; 

Boost-Extended Format String Syntaxthe example在文檔的regex_replace結束。

+0

你測試過了嗎?在我的系統上,這會返回意外的結果通過(?1nl)(?2nl)流(?1nl)(?2nl)(?1nl)(?2nl)覆蓋(?1nl)(?2nl)Windows 7 VS 2008 Express – user754425 2011-05-20 02:29:33

+0

糟糕。我忘了boost :: format_all match_flag,它啓用了(?Ntext)語法。我糾正了代碼並在g ++下測試了它。抱歉。 – SCFrench 2011-05-20 14:09:47