通过字符串中的修改版本替换字符

时间:2016-09-24 15:13:48

标签: c++ regex replace

我想用正则表达式替换

替换输入字符串中的下面的字符(或&&和||的子字符串)
+ - ! ( ) { } [ ] ^ " ~ * ? : \ && ||

如何在构造std :: regex?

中编写此请求

例如,如果我有

"(1+1):2"

我希望输入:

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

最终代码如下所示:

  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 ?

1 个答案:

答案 0 :(得分:1)

您可以将std::regex_replace与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;
}

打印

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