使用提升精神

时间:2017-02-03 08:10:56

标签: c++ boost boost-spirit boost-spirit-qi

我正在尝试解析中间带有非数字的字符串中的数值。是否有可能以提升精神来做到这一点?例如,

std::string s = "AB1234xyz5678C9";
int x = 0;
boost::spirit::qi::parse(s.begin(), s.end(), /* Magic Input */, x);
// x will be equal 123456789

3 个答案:

答案 0 :(得分:4)

有点黑客:

weird_num = as_string[ skip(alpha) [+digit] ] [_val = stol_(_1) ];

这要求您调整std::stol以用于语义操作:

Live On Coliru

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

BOOST_PHOENIX_ADAPT_FUNCTION(long, stol_, std::stol, 1);
namespace qi = boost::spirit::qi;

int main()
{
    std::string const s = "AB1234xyz5678C9";
    qi::rule<std::string::const_iterator, long()> weird_num;

    {
        using namespace qi;
        weird_num = as_string[ skip(alpha) [+digit] ] [_val = stol_(_1) ];
    }

    long x = 0;
    if (boost::spirit::qi::parse(s.begin(), s.end(), weird_num, x))
        std::cout << "Got it: " << x << "\n";
}

打印

Got it: 123456789

答案 1 :(得分:1)

我认为这可以轻松完成,但是,这是使用boost::spirit的工作变体。

#include <string>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/spirit/include/qi.hpp>

struct integer_collector
{
public:
   void collect(int v) const
   {
      stream << v;
   }

   int get() const
   {
      int result = 0;
      stream >> result;
      return result; 
   }
private:
   mutable std::stringstream stream;
};

int main()
{
   using namespace boost::spirit::qi;
   std::string s = "AB1234xyz5678C9";
   integer_collector collector;
   int x = 0;
   boost::spirit::qi::parse(s.begin(), s.end(),    
   *(omit[*alpha] >> int_ >> omit[*alpha])
   [boost::bind(&integer_collector::collect, boost::ref(collector), 
   boost::placeholders::_1)]);
   x = collector.get();
   std::cout << x << std::endl;
}

live

答案 2 :(得分:1)

这是一种方式:

namespace qi = boost::spirit::qi;

std::string s = "AB1234xyz5678C9";
int x = 0;
auto f = [&x](char c){ if (::isdigit(c)) x = x * 10 + (c - '0'); };

qi::parse(s.begin(), s.end(), +(qi::char_[f]));

[编辑] 或者,没有isdigit:

auto f = [&x](char c){ x = x * 10 + (c - '0'); };

qi::parse(s.begin(), s.end(), +(qi::char_("0-9")[f] | qi::char_));

[编辑2] 或者,没有lambda:

#include "boost\phoenix.hpp"
...

namespace phx=boost::phoenix;

qi::parse(s.begin(), s.end(),+(qi::char_("0-9")
      [phx::ref(x) = phx::ref(x) * 10 + qi::_1 - '0'] | qi::char_));

[编辑3] 或者,使用递归规则:

qi::rule<std::string::iterator, int(int)> skipInt =
    (qi::char_("0-9")[qi::_val = qi::_r1 * 10 + (qi::_1 - '0')]
    | qi::char_[qi::_val = qi::_r1])
       >> -skipInt(qi::_val)[qi::_val = qi::_1];

qi::parse(s.begin(), s.end(), skipInt(0), x);
相关问题