Qstring: How to use regexp to slip words every two characters.



  • E.p slip QString("123456") into ("12", "34", "56");
    and slip QString("1234567") into (“12”, "34", "56", "7")


  • Qt Champions 2017

    Hi
    If its always every two char then you can just loop over it.

    
      QString Input = "1234567";
      QString Out;
      for (int c = 0; c < Input.length(); ++c) {
        Out += Input[c];
        if ( c % 2)
          Out += " ";
      }
    
      qDebug() << Out;
    
    "12 34 56 7"
    
    


  • No sure why you want to use regular expressions (@mrjj 's solution would be faster), but...

    You can't use QString::split() because those methods take a separator, and you have none. So you'd have to use QRegularExpression::globalMatch() instead, like:

    QStringList parts;
    QRegularExpressionMatchIterator i = QRegularExpression("..?").globalMatch(QString("1234567"));
    while (i.hasNext()) {
       parts << i.next().captured(0);
    }
    qDebug() << parts;
    

    Outputs:

    ("12", "34", "56", "7")
    

    But yeah, for such a simple case, some simple index-based loop, like @mrjj suggested, would be much more efficient.

    Cheers.



  • @mrjj Is it possible use regexp to make it?


  • Qt Champions 2017

    @doodle
    @Paul-Colby version is the regexp version.
    Even more verbose I think its more solid
    as input can be much more different and it still works :)



  • @Paul-Colby Thanks!
    I need to process some Qstring like this " 12 ab, 1a 2ab f 12efa ", and I want to convert it to QStringList like this ("12", "ab", "1a", "2a", "b", "f", "12", "ef", "a").

    QString string("  12 ab, 1a, 2ab f 12efa    ");
        QStringList list;
        list = string.split(QRegularExpression("[\\s|,]"), QString::SkipEmptyParts);
    

    Outputs:

    ("12", "ab", "1a", "2ab", "f", "12efa")
    

    So if the regexp is able to split every two , I can make it just with

    QString::split
    


  • @doodle said in Qstring: How to use regexp to slip words every two characters.:

    I need to process some Qstring like this " 12 ab, 1a 2ab f 12efa ", and I want to convert it to QStringList like this ("12", "ab", "1a", "2a", "b", "f", "12", "ef", "a").

    QStringList parts;
    QRegularExpressionMatchIterator i = QRegularExpression("[^\\s,]{1,2}").globalMatch(QString(" 12 ab, 1a 2ab f 12efa "));
    while (i.hasNext()) {
       parts << i.next().captured(0);
    }
    qDebug() << parts;
    

    Output:

    ("12", "ab", "1a", "2a", "b", "f", "12", "ef", "a")
    

    Cheers.



  • @Paul-Colby @mrjj Thanks!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.