⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

QRegExp replace every second character with a whitespace (blank)?

  • Hi there,

    i want to insert a whitespace (blank) after every second character in a QString.
    Years ago in Java i did it this way: String.replaceAll("(.{2})(?!$)", "$1 ")

    Now i tried to transfer it to Qt and tried it thsi way:

    QString myString = some Data.
    myString.replace(QRegExp("(.{2})(?!$)"), "$1 ");

    But it did not replace it correctly. For example the input is something like this: 34C9FG63R2DE9H88Z and the output should be 34 C9 FG 63 R2 DE 9H 88 Z
    but with my soluton above i got: $1 $1 $1 $1 $1 $1 $1 $1 Z".

    So where is the problem? I think Qt handles the replace in another way like Java.

  • If you are using Qt5 then use QRegularExpression instead of QRegExp

    instead of $1 you should use \1 (escaped so \\1)

    otherwise, more straightforward, you can use:

        const int everyOther = 2;
        for(int i=everyOther;i<testStr.size();i+=everyOther+1)
                testStr.insert(i,' ');

  • ah thanks - using \\1 instead of $1 works as i want it.

    And thanks for the other solution with the For-Loop.

Log in to reply