假设我的字符串是“g500() g600() g200()\n g1()”,我想输出“g1() g2() g3()\n g4()”。
我试过使用正则表达式来这样做,但这给了每个出现相同的值。
#include<iostream>
#include<regex>
#include<string>
void renameGates(std::string& qt_prims, int& gate_id){
std::string s("g.*?\\(");
std::regex re(s);
qt_prims=std::regex_replace(qt_prims,re,std::string("g"+std::to_string(gate_id)+ "("));
++gate_id;
std::cout<<qt_prims;
//should print "g1() g2() g3()\n g4()" but prints "g0() g0() g0()\n g0()"
}
int main(){
std::string str="g500() g600() g200()\n g1()";
int x=0;
renameGates(str,x);
}
但是 g 的所有值都得到相同的值。我曾尝试阅读有关 std::regex_replace 的 c++ 文档,但函数签名确实很神秘。我不知道我需要哪个版本。
最佳答案
它不会像您计划的那样工作。正则表达式将替换所有内容。或者,如果字符串中的模式数量已知,您可以使用反向引用($1、$2、$3 等)。
你也会遇到数数的困难。替换字符串将被创建一次,计数器将始终具有相同的值。
所以我们需要使用不同的方法使用 std::regex_search.
。我们搜索我们的模式,然后获取前缀并添加新的 g()。
然后我们以后缀继续循环操作。
就是这样。
请看下面的例子:
#include<iostream>
#include<regex>
#include<string>
void renameGates(std::string& qt_prims, int& gate_id){
// Define a std::regex to search for g then some digits and brackezs
std::regex re("g\\d+\\(\\)");
// Here we will receive the submatches
std::smatch sm{};
// Make a local copy
std::string tmp{qt_prims};
// Reset resulting value
qt_prims.clear();
// Search all g-numbers
while (std::regex_search(tmp, sm, re)) {
// Build resulting string
qt_prims = qt_prims + std::string(sm.prefix()) + "g" + std::to_string(gate_id++) + "()";
// Continue to search with the rest of the string
tmp = sm.suffix();
}
// If there is still a suffix, add it
qt_prims += sm.suffix();
// Debug output
std::cout << qt_prims << "\n";
}
int main(){
std::string str="g500() g600() g200()\n g1()";
int x=0;
renameGates(str,x);
}
关于C++ Regex 一个一个替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193450/