0

I was attending to replace some characters in an abnormal json string in order to make it normal, so i used regex to match it and replace it in line, the matched character need to be transformed, so is there any method to make "matching" and "transforming" in one function? code below:

std::string replace(std::smatch match) {
    std::string str = match.str();
    return "[" + str + "]";
}
int main(){
    std::string str = R"({"key":"v\"a\"lue","key2":"v"a"lue2"})";
    std::istringstream iss(str);  
    stringstream output;
    std::string token;
    while (std::getline(iss, token, ',')) {  
        std::cout << token << std::endl;  
        std::regex pattern("\\:\\s*\"(.*)\"");
        std::string tokenAfter = std::regex_replace(token, pattern, replace);
        output << tokenAfter;
    }
    cout << output.str();
    return 0;
}

compile infomation: enter image description here

error occurred:

error: no matching function for call to 'regex_replace(std::string&, std::__cxx11::regex&, <unresolved overloaded function type>)'x86-64 gcc 12.2 #1

please guide me to my goal, thanks in advance!

Jim
  • 767
  • 1
  • 10
  • 24
  • Try using `std::regex_replace(token, pattern, "[$0]");` – kiner_shah Mar 09 '23 at 07:16
  • What is your expected output for the given input? – kiner_shah Mar 09 '23 at 07:19
  • Thanks, but adding [] just a test, there could be some more comlicated opeation, for example, to remove the extra quota! – Jim Mar 09 '23 at 07:20
  • You can use `$0` or `$&` for that in your function and then just call it. Even if it's some complicated replace, I don't think you need a function for that, it can be a standalone string. – kiner_shah Mar 09 '23 at 07:21
  • expected: {"key":"value","key2":"value2"}, but origin json string could be long and complicated! – Jim Mar 09 '23 at 07:22

1 Answers1

0

There is no version of std::regex_replace that takes a function or other callable for the format parameter. See here: https://en.cppreference.com/w/cpp/regex/regex_replace

In every version the parameter is either of type std::string or const CharT* with the note that:

fmt - the regex replacement format string, exact syntax depends on the value of flags

Then you can click on the link to the flags type, where you can find a link to the ECMAScript syntax documentation (this is the default syntax).

Frodyne
  • 3,547
  • 6
  • 16