Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QRegExp replace every second character with a whitespace (blank)?
QtWS25 Last Chance

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

Scheduled Pinned Locked Moved Solved General and Desktop
regexqstring
3 Posts 2 Posters 1.2k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • O Offline
    O Offline
    Opa114
    wrote on last edited by
    #1

    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.
    thanks!

    1 Reply Last reply
    0
    • VRoninV Offline
      VRoninV Offline
      VRonin
      wrote on last edited by VRonin
      #2

      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,' ');
      

      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
      ~Napoleon Bonaparte

      On a crusade to banish setIndexWidget() from the holy land of Qt

      1 Reply Last reply
      2
      • O Offline
        O Offline
        Opa114
        wrote on last edited by
        #3

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

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

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved