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