Qt World Summit: Submit your Presentation

How to split a string until nth space?

  • Hi,
    I have following string:

    QString str = "DRIVER_STAT.LEG1_LO_ERR         00000004	00000000	00000001	00000000	RO	LEG1 Driver Low Error";

    There are spaces and tabs between words and there are always 7 fields. I want to save them to a QStrginList but not affecting the last sentence, i. e. the desctiption "LEG1 Driver Low Error" must be one string. It shoult look like this:

    ["DRIVER_STAT.LEG1_LO_ERR"], ["00000004"], ["00000000"], ["00000001"], ["00000000"], ["RO"], ["LEG1 Driver Low Error"]

    How can I do that? What is the correct Regex for that?

  • Lifetime Qt Champion

    Are any of the fields fixed size?

    Also ["LEG1 Driver Low Error"]

    Can contain both space and/or tabs?

    So we do not know what separator is used - it can be mixed?

  • Hi,
    Thanks for reply.
    To explain more clearly, the seperator is normaly tab character except the first word:


  • @kahlenberg said in How to split a string until nth space?:


    Means, that the after the first group the separators could be any number of whitespace characters or blanks only? As far as I remember \s matches any whitespace char

    • A space character
    • A tab character
    • A carriage return character
    • A new line character
    • A vertical tab character
    • A form feed character

  • Sory, I meant only one or more space character with \s+ and only one or more tab character with \t+. There are no \r, \n characters, There are only spaces or tabs.

  • Hi,
    you can try this:

       QStringList l1 = str.split('\t', QString::SkipEmptyParts);
       QStringList l2 = l1.takeFirst().split(' ', QString::SkipEmptyParts);

  • Wow!
    Thank you very much. It works!

  • @kahlenberg

    You could als try with a RegularExpression like this:

    str = str.replace(QRegularExpression("[ ]+(.*$)"),"\t\\1").replace(QRegularExpression("[ ]+")," ")
    QStringList list = str.split(QRegularExpression("\t+"));

    This will also remove multiple spaces in the last text block

  • Moderators

    QStringList list = str.split(QRegularExpression("\s+(?=[0-9]|RO|LEG1)"));

Log in to reply