Question

I have a QString with some number inside it, for example

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

How can I extract number from the string?

EDIT:

This function seems to work, using regexp in replies:

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();
}
Was it helpful?

Solution

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

edit: sorry, messed up with the brackets, now it should work.

OTHER TIPS

I would write a simple function for that:

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";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top