Home > Software engineering >  Replace a sub string
Replace a sub string

Time:01-06

I m trying to replace a substring between two tags

int main(int argc, char* argv[]) {
    
    std::string s("<list>test</list>");
    std::regex e("<list>(.*)</list>");  
    std::string result;
    std::regex_replace(std::back_inserter(result), s.begin(), s.end(), e, "$1");
    std::cout << result;  
}

The output from this program is test. It replaces the tags instead of test.

I would like to get the output as <list></list>

Can you advise what is wrong here?

CodePudding user response:

It seems like you are selecting the first group value (through $1), which is test in your given string. I assume, what you are trying to do, is to replace the group which matches test, with another string. You could do something like this:

#include <string>
#include <algorithm>
#include <iostream>
#include <regex>

int main(int argc, char* argv[]) {
    // Input string.
    std::string s("<list>test</list>");
    // Matching regex. Note the additional groups.
    std::regex e("(<list>)(.*)(</list>)");
    // String replacement. 
    std::string replacement("replacement");

    std::string result;
    std::regex_replace(std::back_inserter(result), s.begin(), s.end(), e, "$1" replacement "$3");

    std::cout << result;

    return 0;
}

Which will rebuild the matched beginning ($1) and closing ($3) tag with the replacement string in between ($2).

Result:

<list>replacement</list>
  •  Tags:  
  • Related