Reputation: 9114
I need to replace a string of the type T1.9
with the string unit19
. The number of digits could vary e.g.T34.999
should become unit34999
. Here is my progress:
std::regex e ("^(T\d+\.\d+)$");
std::string result (std::regex_replace(version, e, "") );
What should I write for format? Or is the approach to replace the string in one, no two, iterations, wrong?
Upvotes: 2
Views: 162
Reputation: 626923
You need to adjust the capturing groups in the pattern and use backreferences in the replacement pattern:
^T([0-9]+)[.]([0-9]+)$
and replace with unit$1$2
.
See the regex demo
#include <iostream>
#include <regex>
using namespace std;
int main() {
std::vector<std::string> strings;
strings.push_back("T34.999");
strings.push_back("T1.9");
std::regex reg("^T([0-9]+)[.]([0-9]+)$");
for (size_t k = 0; k < strings.size(); k++)
{
std::cout << std::regex_replace(strings[k], reg, "unit$1$2") << std::endl;
}
return 0;
}
Upvotes: 2