c++ - 用字符串中的修改版本替换字符

标签 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 ?

最佳答案

您可以使用 std::regex_replace捕获:

#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

关于c++ - 用字符串中的修改版本替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39677887/

相关文章:

java - 频繁执行的表达式是否缓存了它的结果?

c++ - 专用于 const char * 的模板也会接受 char * 吗?

html - 如何连续点击满足特定条件的链接?

matlab - 在 MATLAB 中以 0 到 1 和 1 到 0 的不同概率替换向量的元素

replace - 替换序言中的部分表达式

用于搜索并替换为 "match words only"选项的 Python 脚本

c++ - float 的小数部分最多有多少位 10 位数字

c++ - 使用 C++ 容器最小化内存开销(std::map 和 std::vector 太贵了)

javascript |正则表达式搜索网址

javascript - 正则表达式模式不允许除下划线外的特殊字符