使用Boost c++库将正则表达式替换为自定义替换



我可以使用Boost库的表达式来做一些正则表达式替换,像这样:

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

我需要的是将捕获的部分替换为某个转换函数的结果,例如

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

所以上面提供的示例的结果将是cb gf.

你认为实现这一点的最好方法是什么?

提前感谢!

使用

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;
}

生活例子

在文档中有所有关于regex_replace函数视图的描述/要求

将formatter函数传递给regex_replace。注意需要取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);

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

最新更新