Quick Q: C++ regex: Conditional replace

Quick A: Use regex_token_iterator

Recently on SO:

C++ regex: Conditional replace

Use regex_token_iterator


#include <regex>
#include <string>
#include <sstream>
#include <set>
#include <map>

std::string replacer(std::string text) {
    std::string output_text;
    std::set<std::string> keywords = { "foo", "bar" };
    std::map<std::string, int> ids = {};

    int counter = 0;
    auto callback = [&](std::string const& m){
        std::istringstream iss(m);
        std::string n;
        if (iss >> n)
        {
            if (keywords.find(m) != keywords.end()) {
                output_text += m + " ";
            }
            else {
                if (ids.find(m) != ids.end()) {
                    output_text += "ID" + std::to_string(ids[m]) + " ";
                }
                else {
                    // not found
                    ids[m] = counter;
                    output_text += "ID" + std::to_string(counter++) + " ";
                }
            }
        }
        else
        {
            output_text += m;
        }
    };

    std::regex re("\\b\\w*\\b");
    std::sregex_token_iterator
        begin(text.begin(), text.end(), re, { -1, 0 }),
        end;
    std::for_each(begin, end, callback);
    return output_text;
}

 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.