Find the number inside QString

I have a QString with some number inside it, like

first_34.33string
second-23.4string // In this case number is negative

How can I extract a number from a string?

EDIT:

This function works using regexp in the answers:

float getNumberFromQString(const QString &xString)
{
  QRegExp xRegExp("(-?\\d+(?:[\\.,]\\d+(?:e\\d+)?)?)");
  xRegExp.indexIn(xString);
  QStringList xList = xRegExp.capturedTexts();
  if (true == xList.empty())
  {
    return 0.0;
  }  
  return xList.begin()->toFloat();
}
+4
source share
2 answers

This should work for real numbers: QRegExp("(-?\\d+(?:[\\.,]\\d+(?:e\\d+)?)?)")

Edit: sorry, spoiled by brackets, now it should work.

+4
source

I would write a simple function for this:

static double extractDouble(const QString &s)
{
    QString num;
    foreach(QChar c, s) {
        if (c.isDigit() || c == '.' || c == '-') {
            num.append(c);
        }
    }
    bool ok;
    double ret = num.toDouble(&ok);
    if (ok) {
        return ret;
    } else {
        throw "Cannot extract double value";
    }
}
+1
source

Source: https://habr.com/ru/post/1536430/


All Articles