tags:

views:

69

answers:

2

My code:

#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
);

This is what I see:

{…}{y}

Thus, only the first occurrence replaced. Why? How to solve it?

A: 

You might want to use replace_all_regex_copy() instead of replace_regex_copy()

f4
many thanks! :)
Vincenzo
A: 

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. (-:

Huw Walters