Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract number from Alphanumeric QString

I have a QString of "s150 d300". How can I get the numbers from the QString and convert it into integer. Simply using 'toInt' is not working.

Let say, from the QString of "s150 d300", only the number after the alphabet 'd' is meaningful to me. So how can I extract the value of '300' from the string?

Thank you very much for your time.

like image 799
Wan Shahmisufi Wan Jamaludin Avatar asked May 05 '26 00:05

Wan Shahmisufi Wan Jamaludin


2 Answers

Why all the trouble if you can just do:

#include <QDebug>
#include <QString>

const auto serialNumberStr = QStringLiteral("s150 d300");

int main()
{
    const QRegExp rx(QLatin1Literal("[^0-9]+"));
    const auto&& parts = serialNumberStr.split(rx, QString::SkipEmptyParts);

    qDebug() << "2nd nbr:" << parts[1];
}

Prints out: 2nd nbr: "300"

like image 197
DrumM Avatar answered May 09 '26 00:05

DrumM


One possible solution is to use regular expressions as shown below:

#include <QCoreApplication>

#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString str = "s150 dd300s150 d301d302s15";

    QRegExp rx("d(\\d+)");

    QList<int> list;
    int pos = 0;

    while ((pos = rx.indexIn(str, pos)) != -1) {
        list << rx.cap(1).toInt();
        pos += rx.matchedLength();
    }
    qDebug()<<list;

    return a.exec();
}

Output:

(300, 301, 302)

Thanks to the comment of @IlBeldus, and according to the information QRegExp will be deprecated, so I propose a solution using QRegularExpression:

Another solution:

QString str = "s150 dd300s150 d301d302s15";

QRegularExpression rx("d(\\d+)");

QList<int> list;
QRegularExpressionMatchIterator i = rx.globalMatch(str);
while (i.hasNext()) {
    QRegularExpressionMatch match = i.next();
    QString word = match.captured(1);
    list << word.toInt();
}

qDebug()<<list;

Output:

(300, 301, 302)
like image 23
eyllanesc Avatar answered May 09 '26 01:05

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!