Search code examples
c++boost-spiritboost-spirit-qi

limit qi::hex parser to 2 chars


I'm parsing string with escaped characters, I want '\xYY' to be parsed as character with YY code. This is as far as i understand qi::hex for. But I need only two subsequent chars to be parsed, not more. So "\x30kl" is parsed correctly, but not "\x30fl", because qi::hex parse '30f', not just '30'. The question is how to limit hex parsing length?

This is my grammar:

template <typename Iterator>
struct gram : qi::grammar<Iterator, std::string(), ascii::space_type> {
    gram() : gram::base_type(start) {    
        start %= "'" >> *(string_char) >> "'";
        string_char = ("\\" >> qi::char_('\'')) | 
                      ("\\x" >> qi::hex)        |
                      (qi::print - "'");
    }    
    qi::rule<Iterator, std::string(), ascii::space_type> string_char, start;
};

And this is link to Coliru: http://coliru.stacked-crooked.com/a/ba96c7410c772c87

Thanks!


Solution

  • Use:

    qi::int_parser<unsigned char, 16, 1, 2> hex2_;
    

    Or if you require exactly 2, make it

    qi::int_parser<unsigned char, 16, 2, 2> octet_;
    

    Note that unsigned char is now the exposed attribute. You can use char if you prefer (or int...)