2010-05-17 85 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},那么......在这种情况下,请忽略我的帖子。 ( - :

相关问题