I am using boost::spirit::qi
to parse a number that can be optionally followed by metric prefixes. For example, "10k"
for 10000
. The k
should be treated in a case insensitive fashion. I can simply match the prefix using:
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
using iter = std::string::const_iterator;
class MyGrammar : public qi::grammar<iter>
{
public:
MyGrammar()
: MyGrammar::base_type(start)
{
start = qi::double_ >> suffix | qi::double_;
suffix = qi::char_('K') | qi::char_('k');
}
qi::rule<iter> suffix;
qi::rule<iter> start;
};
What I would like to do is to use the above code to not only parse/match the format, but to use whatever method is appropriate to convert the suffix (e.g., k
) to a numerical multiplier and return a double
.
How does one achieve this using boost qi?
What Nail said works. I'd suggest using symbols to be more efficient and potentially more correct (e.g. with overlapping suffixes). Here's an example to parse time units:
Custom validate function to parse std::chrono::milliseconds via Boost program options
In your example I'd write something like Live On Coliru
Printing