Split a QString and remove the rest



  • I want to split a QString using a delimiter and get the text after, removing everything that comes after that text, for example.

    QString a = "@john.foo";
    QString b = "@john_foo";
    QString c = "@john foo";
    QString d = "@john!foo";
    
    auto result = a.split('@').last();
    

    I want the result to be only john in all cases above. I want to remove everything that comes after, if it's a space or any other character that is not alphabetic or numeric.



  • Just checking, what would you expect from:

    QString e = "mary@jane@john@peter_russell";
    

    jane? or peter?



  • @Paul-Colby - Always the last one, and about the "_", it would be valid, we can see it as a replacement for a space.



  • You could use a QRegExp (Qt 4.8) or a (QRegularExpression (Qt 5.x))[http://doc.qt.io/qt-5/qregularexpression.html], this would allow you to capture any alphanumeric character following @.



  • @Volebab said:

    @Paul-Colby - Always the last one, and about the "_", it would be valid, we can see it as a replacement for a space.

    I take that to mean "peter".

    As @JohanSolo said, you can use QRegularExpression - that would probably be easiest, but not necessarily fastest (depends on which is more important to you).

    For example:

    QString one(const QString &input)
    {
        const QRegularExpression re(".*@([A-Za-z0-9]+)");
        const QRegularExpressionMatch match = re.match(input);
        return match.hasMatch() ? match.captured(1) : QString();
    }
    
    ...
        QString a = "@john.foo";
        QString b = "@john_foo";
        QString c = "@john foo";
        QString d = "@john!foo";
        QString e = "mary@jane@john@peter_russell";
    
        qDebug() << "a" << one(a);
        qDebug() << "b" << one(b);
        qDebug() << "c" << one(c);
        qDebug() << "d" << one(d);
        qDebug() << "e" << one(e);
    

    Outputs:

    a "john"
    b "john"
    c "john"
    d "john"
    e "peter"
    


  • You were right, regex is the best option here. I asked because I wanted to know if there's any alternative.
    Thank you guys.



  • And a (possibly) faster version without using regular expressions:

    QString two(const QString &input)
    {
        const int startPos = input.lastIndexOf('@', -2) + 1;
        if (startPos <= 0) return QString(); // Failed to match.
        int endPos;
        for (endPos = startPos + 1;
             (endPos < input.size()) && (input.at(endPos).isLetterOrNumber());
             ++endPos);
        return input.mid(startPos, endPos - startPos);
    }
    

    Output is identical to the above version. There may be differences between to two, but not in the given test scenarios ;)

    Cheers.


Log in to reply
 

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