boost::regex search and replace

1k Views Asked by At

I'm writing a program that does string manipulations with boost::regex. In all the cases I need the functionality of regex_search, but only specific cases need regex_replace. Is there a way to combine the two so that replacing doesn't redo the work of searching?

I know that after calling

boost::regex re;
std::string str, fmt;
// . . .
boost::smatch match;
regex_search( str, match, re );

match contains information about matching, but

match.format( fmt );

doesn't do what

regex_replace( str, re, fmt );

does.

1

There are 1 best solutions below

0
On

Perhaps use a dynamic replacement: C++ boost regex replace with conditions

The sample there has a c++03, c++11 variants with named/unnamed submatches.

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

int main() {
    std::string pattern = "dddd, mmmm d, yyyy";
    pattern = boost::regex_replace(pattern, boost::regex("(dddd)|(d)|(mmmm)|(yyyy)"), [](auto& match)->std::string{
        if (match.str() == "dddd")
            return "Tuesday";

        if (match.str() == "d")
            return "26";

        if (match.str() == "mmmm")
            return "December";

        if (match.str() == "yyyy")
            return "2016";

        return "";
    });

    std::cout << "Result: " << pattern << "\n";
}