2

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?

1 Answer 1

2

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

A test at IDEONE:

#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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you a lot. I always struggle with regular expressions. This time I managed to customize your example for my other regex tasks of today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.