Important: Please read the Qt Code of Conduct -

[SOLVED] how to use QRegExp to find some continue spaces?

  • I have a string
    178542 5 5 5 0 1447 33386 1452 1452 44585 44631 1452 44576
    in the sample it has 13 sections, in the real work, it may contain different sections

    in the sample, one section contains 8 characters, and each section starts by space including the first section, so the string starts by space.

    I need to output a string in the same format, so I need to find how long each section is.

    I tried to use QRegExp, my idea is that: the start position of the 2nd continue spaces is the length of 1st section. Then I tried:
    but I failed, it returns 0 which is the start of the 1st continue spaces. Then I tried to use
    to find the 2nd/3rd/4th match, but every one returns -1 which means no match.

    I feel confused, it seems that QRegExp works not the same as other regular expression tool. Can any one help me?

  • Why not simply do:
    @QStringList list = str.split(" ", QString::SkipEmptyParts);@

    Now you have a list containing only the parts between the spaces, so you can easily walk through the list and check QString::length() of each part...

    I think the same can be done with with RegExp, but I would use QRegExp("\S+") with an upper case S, which matches only characters that are not whitespaces. Then you could do:
    @QRegExp reg("\S+")
    int pos = reg.indexIn(str, 0);
    while(pos >= 0)
    int len = reg.cap(0).length(); //This returns the length of each part
    pos = reg.indexIn(str, pos+1);

    Still I think QString::split() is more straight forward here...

  • So you have numbers right justified in fixed width columns and you want to work out the widths of the columns, which includes the leading spaces.

    QString line(" 178542 5 5 5 0 1447 33386 1452 1452 44585 44631 1452 44576");

    QList<int> widths;
    QRegExp re("\s+\S+");
    int pos = 0;
    while ((pos = re.indexIn(line, pos)) != -1) {
    widths << re.matchedLength();
    pos += re.matchedLength();
    qDebug() << widths;
    // (12, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8)

    Of course, it won't work if some of the columns are "empty" or if the column can contain spaces.

Log in to reply