0

I've have a method in a class that takes a QString and, using a regular expression, it return the first float number (positive or negative) included into the string. This is the method:

float MyClass::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();
}

It works, but now I need to avoid Qt and doing the same thing using only boost. I've created a method using boost, but it does not work:

#include <boost/regex.hpp>
#include <boost/spirit/include/qi.hpp>

// other class methods

float Importer::getNumberFromString(const std::string &sString)
{
  float fElevation = 0.0f;
  boost::regex e("(-?\\d+(?:[\\.,]\\d+(?:e\\d+)?)?)");
  boost::smatch what;
  if(boost::regex_match(sString, what, e, boost::match_extra)) {
    if (false == what.empty()) {
      boost::spirit::qi::parse(what[0].str().begin(), what[0].str().end(), fElevation);
    }
  }
  return fElevation;
}

The problem is that, given the same string value to both methods (for example "lpda_-30.dat"), the Qt version works, while the boost version fails the boost::regex_match function. I've copied the regular expression, so I don't know why it fails. I must convert the regular expression before use it with boost::regex, or there's something wrong in the code?

Jepessen
  • 11,744
  • 14
  • 82
  • 149

1 Answers1

0

I've resolved.

I've taken inspiration from this post and I've changed method implementation, not the regex:

float Importer::getNumberFromString(const std::string &sString)
{
  float fElevation = 0.0f;
  boost::regex e("(-?\\d+(?:[\\.,]\\d+(?:e\\d+)?)?)");
  boost::sregex_iterator it(sString.begin(), sString.end(), e);
  boost::sregex_iterator end;
  if (it != end)
  {
    std::string sValue(it->str());
    boost::spirit::qi::parse(sValue.begin(), sValue.end(), fElevation);
  }
  return fElevation;
}
Community
  • 1
  • 1
Jepessen
  • 11,744
  • 14
  • 82
  • 149