Search code examples
c++qtqt4qt5

Regex split string every two characters


I need to process some QString that looks like this " 12 ab, 1a 2ab f 12efa ", I want to convert it to a 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);

Output:

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

So if the regexp is able to split every two, I can make it just with QString::split. How can I do this?


Solution

  • It's easier to use a different regex, then use a QRegularExpressionMatchIterator to add the matches to a QStringList.

    The ([\\w]{1,2}]) regex will match and capture a pair of consecutive word characters or a single word character.

    Check out the following code and see if this is what you need.

    #include <QString>
    #include <QStringList>
    #include <QDebug>
    #include <QRegularExpression>
    
    int main(void)
    {
        QString string("  12 ab, 1a, 2ab f 12efa    ");
    
        QRegularExpression re("([\\w]{1,2})");
        QRegularExpressionMatchIterator i = re.globalMatch(string);
    
        QStringList list;
        while (i.hasNext()) {
            QRegularExpressionMatch match = i.next();
            QString word = match.captured(1);
            list << word;
        }
    
        qDebug() << list;
    
        return 0;
    }