Search code examples
c++regexqtqstring

QString, Parse and replace some specific sections


Suppose I have a string like this:

QString str = "23+34-343+$T$-3+$OPC$";

I want to replace every sections which are enclosed by two $ will be replaced with %0, %1 and so on. So the above example would be : "23+34-343+%0-3+%1"

I can detect the sections by using QRegularExpression and with this pattern: "\$.+?\$"

What is the best and most optimized way (not to use loops and indices) to replace those sections with %0, %1, %2 and so on.


Solution

  • How is this:

    QString str = "23+34-343+$T$-3+$OPC$";
    
    QRegExp rx;
    rx.setMinimal(true);
    rx.setPattern("\\$.+\\$");
    str.replace(rx, "X");           //First replace every pattern with something like 'X'
    
    for(int i=0 ;str.indexOf("X")!=-1; i++)
        str.replace(str.indexOf("X"), 1,"%"+QString::number(i));