boost::regex_replace() replaces only first occurrence, why?
My code:
#include <string>
#include <boost/algorithm/string/regex.hpp>
std::cout << boost::algorithm::re开发者_如何转开发place_regex_copy(
"{x}{y}", // source string
boost::regex("\\{.*?\\}"), // what to find
std::string("{...}") // what to replace to
);
This is what I see:
{…}{y}
Thus, only the first occurrence replaced. Why? How to solve it?
You might want to use replace_all_regex_copy()
instead of replace_regex_copy()
The regular expression * (zero or more of the previous) operator matches as many characters from the source string as possible, where the *? operator matches as few characters as possible.
So the .*?
in boost::regex("\\{.*?\\}")
matches only the x
in your source string (it wouldn't even do that, except that you've told it to match }
afterwards) and the entire expression matches {x}
.
If you actually wanted to match the entire string, you should use boost::regex("\\{.*\\}")
instead.
Unless you actually wanted to replace both {x}
and {y}
with {...}
, that is ... in which case, please ignore my post. (-:
精彩评论