将字符串中的字符替换为其修改后的版本

Replacing characters by a modified version of them in a string

本文关键字:修改 版本 替换 字符串 字符      更新时间:2023-10-16

我想替换下面的字符(或&&在输入字符串中使用正则表达式替换

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

如何在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 ?

您可以使用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