public
Authored by avatar bzctoons :alien:

split a string as list with double quotes (") handling

stringToList.cpp 1.18 KiB
#include <QDebug>
#include <QUrl>

/**
 * @brief stringToList
 * @abstract split a string as list with double quotes (") handling
 * @param line
 * @return QStringList
 */

QStringList stringToList(QString line) {
    QStringList list;
    QRegExp     rx("\"([^\"]*)\"");
    int         pos = 0;
    while ((pos = rx.indexIn(line, pos)) != -1) {
        list << rx.cap(0);
        pos += rx.matchedLength();
    }
    for (auto l : qAsConst(list)) {
        QString ol = l;
        l.replace(" ", "<SPC>");
        line.replace(ol, l);
    }

    list.clear();
    QStringList tmp = line.split(' ');
    for (auto l : qAsConst(tmp)) {
        if (l.isEmpty())
            continue;

        list << l.replace("<SPC>", " ");
    }

    return list;
}

int main(int argc, char *argv[]) {
    QStringList l;
    l << "helo"
      << "réda"
      << "multi word"
      << "\\plok\\"
      << "\"plok is my name\\"
      << "SEARCH \"testme please\" LAST_MODIFIED:2 days CREATED:31/12/2020 MAX_SIZE:1M EXT:txt,doc,xlsx TYPE:image OR "
         "text"

        ;
    for (const auto &i : qAsConst(l)) {
        qDebug() << stringToList(i);
        qDebug() << QUrl::toPercentEncoding(i);
    }

    return 0;
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment