Aminos
Aminos

Reputation: 871

Replacing characters by a modified version of them in a string

I want to replace the characters below (or sub-strings for the && and ||)in an input string with regex replace

+ - ! ( ) { } [ ] ^ " ~ * ? : \ && ||

How can I write this request in the construction of the std::regex ?

For example if I have

"(1+1):2"

I want to have an input of :

"\(1\+1\)\:2"

The final code looks something like this :

  std::string s ("(1+1):2");
  std::regex e ("???");   // what should I put here ?

  std::cout << std::regex_replace (s,e,"\\$2"); // is this correct ?

Upvotes: 2

Views: 170

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

You can use std::regex_replace with capture:

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

using namespace std;

int main() {
    regex regex_a("(\\+|-|!|\\(|\\)|\\{|\\}|\\[|\\]|\\^|\"|~|\\*|\\?|:|\\\\|&&|\\|\\|)");
    cout << regex_replace("(1+1):2", regex_a, "\\$0") << endl;
}

This prints

$ ./a.out 
\(1\+1\)\:2

Upvotes: 1

Related Questions