Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a number inside a QString

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();
}
like image 964
Jepessen Avatar asked Mar 20 '23 21:03

Jepessen


1 Answers

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

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

like image 89
Sebastian Lange Avatar answered Mar 31 '23 16:03

Sebastian Lange