I am trying to parse the numeric value from a string with non-digits in between. Is it possible to do it with boost spirit? For example,
std::string s = "AB1234xyz5678C9";
int x = 0;
boost::spirit::qi::parse(s.begin(), s.end(), /* Magic Input */, x);
// x will be equal 123456789
A bit of a hack:
weird_num = as_string[ skip(alpha) [+digit] ] [_val = stol_(_1) ];
This requires you to adapt std::stol
for use in the semantic action:
#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";
}
Prints
Got it: 123456789