我想用正则表达式替换
替换输入字符串中的下面的字符(或&&和||的子字符串)+ - ! ( ) { } [ ] ^ " ~ * ? : \ && ||
如何在构造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 ?
答案 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