muffel
muffel

Reputation: 7370

Using Boost C++ library to do a regex replace with a custom replacement

I can use Xpressive of the Boost library to do some regex replacement like this:

#include <iostream>
#include <boost/xpressive/xpressive.hpp>

void replace(){
    std::string in("a(bc) de(fg)");
    sregex re = +_w >> '(' >> (s1= +_w) >> ')';
    std::string out = regex_replace(in,re,"$1");
    std::cout << out << std::endl;
}

What I need is to replace the captured part by the result of a certain transformation function like e.g.

std::string modifyString(std::string &in){
    std::string out(in);
    std::reverse(out.begin(),out.end());
    return out;
}

so the result of the example provided above would be cb gf.

What do you think would be the best approach to realize this?

Thanks in advance!

Upvotes: 1

Views: 2573

Answers (2)

ecatmur
ecatmur

Reputation: 157374

Pass the formatter function into regex_replace. Note it needs to take const smatch &.

std::string modifyString(smatch const &what){
    std::string out(what[1].str());
    std::reverse(out.begin(),out.end());
    return out;
}

std::string out = regex_replace(in,re,modifyString);

See http://www.boost.org/doc/libs/1_53_0/doc/html/xpressive/user_s_guide.html#boost_xpressive.user_s_guide.string_substitutions

Upvotes: 2

ForEveR
ForEveR

Reputation: 55887

Use

std::string modifyString(const smatch& match){
    std::string out(match[1]);
    std::reverse(out.begin(),out.end());
    return out;
}

void replace(){
    std::string in("a(bc) de(fg)");
    sregex re = +_w >> '(' >> (s1= +_w) >> ')';
    std::string out = regex_replace(in, re, modifyString);
    std::cout << out << std::endl;
}

live example

In documentation there is all about regex_replace function view Desctiption/Requires

Upvotes: 2

Related Questions