boost::regex库中的boost::regex_replace方法学习

    需求:对字符串中的特定字符进行某种变换

    发现python的正则表达式替换处理很好用,感觉C++的regex库应也行,查了一下boost.org文档,结果发现,毕竟是C++,用起来还是有点复杂,应是自己功力不够。

发现网上的例子都是简单的替换,没有回调函数的例子,折腾了好几番,终于实现了简单的回调处理,暂记录下来。代码如下:


#include
#include
#include
#include

class regex_callback
{
public:
    regex_callback() : m_str("=")
    {}

    //template void operator()(const T& what)
    std::string operator()(const boost::smatch& what)
    {
        //m_str = what[0].str() + "=";
        //std::cout << m_str.c_str() << std::endl;
        return  (m_str + what[0].str() + m_str);
    }

    std::string end()
    {
        return m_str;
    }

private:
    std::string m_str;
};

int main()
{
    boost::regex reg("good");
    std::string str = "http://good/good";

    //boost::sregex_iterator it(str.begin(), str.end(), reg);
    //boost::sregex_iterator end;
    
    regex_callback c;
    //std::string strend = for_each(it, end, c).end();
    std::string strend = boost::regex_replace(str, reg, c);
    std::cout << strend.c_str() << std::endl;    
}

=================================================================

boost给出的错误信息:

/usr/include/boost/regex/v4/regex_format.hpp:1023:41: error: no match for call to ‘(cbk) (const boost::match_results<__gnu_cxx::__normal_iterator > >&)’
regex.cpp:7:14: note: candidate is: std::string cbk::operator()(boost::smatch&)

回调的函数操作符,应为const



你可能感兴趣的:(C++)