2010-05-17 95 views
0

我的代碼:boost :: regex_replace()只替換第一次出現,爲什麼?

#include <string> 
#include <boost/algorithm/string/regex.hpp> 
std::cout << boost::algorithm::replace_regex_copy(
    "{x}{y}", // source string 
    boost::regex("\\{.*?\\}"), // what to find 
    std::string("{...}") // what to replace to 
); 

這是我所看到的:

{…}{y} 

因此,只有第一次出現取代。爲什麼?如何解決它?

回答

0

你可能想使用的replace_all_regex_copy()代替replace_regex_copy()

+0

非常感謝!:) – yegor256 2010-05-17 10:28:05

0

正則表達式*(零個或多個之前的)運營商儘可能多的字符從源字符串成爲可能,匹配其中*?運算符儘可能少地匹配字符。

所以.*?boost::regex("\\{.*?\\}")只匹配源字符串在x(它甚至不會做,除非你已經告訴它以後匹配})和整個表達式匹配{x}

如果您確實想匹配整個字符串,則應該使用boost::regex("\\{.*\\}")

除非你真的想用{...}代替{x}{y},那麼......在這種情況下,請忽略我的帖子。 ( - :

相關問題