Boost logo

Boost Users :

From: John Maddock (john_at_[hidden])
Date: 2007-10-27 11:31:57


Golan Trevize wrote:
> I need use regexp. The idea is that I use 'replace', it find some
> text like in expression and this will be an input for function...
> then in function something happen and output of the function replace
> in text the input of the function...
>
> For example I've got text "Solution: 5 and 4". Regular expression is
> "[0-9]" And the function is "add5"
> int add5(int input){return input+5}
> And the output of this function replace the number with number+5...
> And in the end text will be: "Solution: 10 and 9"
>
> In C++ with Boost? I don't know how can I do it...

You need to iterate over the matches and replace each occurance with your
new text, off the top of my head something like:

extern std::string text_to_search;
std::string result_text;
boost::regex r("[[:digit:]]+");

boost::sregex_iterator a(text_to_search.begin(), text_to_search.end(), r),
b;
std::string::const_iterator last_end = text_to_search.begin();

while(a != b)
{
    result_text.append(a->prefix());
    result_text.append(my_transformation(a.str()));
    last_end = (*a)[0].second;
    ++a;
}
result_text.append(last_end, text_to_search.end());

The key part here is my_transformation(x) which should accept a string and
return the new string: use lexical_cast to convert between strings and
numbers as required.

HTH, John.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net