mardi 1 décembre 2015

Infinite loop when using regex_search with std::string

Why does the following code result in an infinite loop?

#include <boost/regex.hpp>

#include <iostream>
#include <string>

int main()
{
  const std::string formula = "LAST_BID_EURUSD$ LAST_ASK_USDJPY$";

  boost::smatch matches;
  boost::regex expr("(LAST_(?:BID|ASK)_.+?\\$)");
  while (boost::regex_search(formula, matches, expr))
  {
    std::cout << std::string(matches[1].first, matches[1].second) << std::endl;
  }
}

If I pass iterators to begin and end of formula instead of the formula itself and update the start one accordingly, all works as expected:

#include <boost/regex.hpp>

#include <iostream>
#include <string>

int main()
{
  const std::string formula = "LAST_BID_EURUSD$ LAST_ASK_USDJPY$";

  auto start = formula.begin();
  auto end = formula.end();

  boost::smatch matches;
  boost::regex expr("(LAST_(?:BID|ASK)_.+?\\$)");
  while (boost::regex_search(start, end, matches, expr))
  {
    std::cout << std::string(matches[1].first, matches[1].second) << std::endl;
    start = matches[0].second;
  }
}

Output

LAST_BID_EURUSD$
LAST_ASK_USDJPY$

The same goes for C++11 regex.

How is it supposed to be used with std::string objects?

Aucun commentaire:

Enregistrer un commentaire