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

Boost Spirit parser rule to parse square brackets


I have to parse a string that can optionally have square brackets in it. For e.g. This can be my token string:

xyz[aa:bb]:blah

I have used rules like

  • +(~qi::char_("\r\n;,="))
  • +(~qi::char_("\r\n;,=") | "[" | "]")
  • +(qi::char_ - qi::char_("\r\n;,="))

But none of them accepts the square brackets. Is there some special handling of [] in the parser?


Solution

  • You need to show the code. Here's a simple tester that shows that all of the parsers succeed and give the expected result:

    Live On Coliru

    #include <boost/spirit/include/qi.hpp>
    #include <iomanip>
    
    namespace qi = boost::spirit::qi;
    
    int main()
    {
        using It = std::string::const_iterator;
    
        for(std::string const input : {"xyz[aa:bb]:blah"})
        {
            qi::rule<It, std::string()> rules[] = {
                +(~qi::char_("\r\n;,=")),
                +(~qi::char_("\r\n;,=") | "[" | "]"),
                +(qi::char_ - qi::char_("\r\n;,=")),
            };
            for(auto const& r : rules)
            {
                std::string out;
                std::cout << std::boolalpha
                          << qi::parse(begin(input), end(input), r, out) << " -> "
                          << std::quoted(out) << "\n";
            }
        }
    }
    

    Printing:

    true -> "xyz[aa:bb]:blah"
    true -> "xyz[aa:bb]:blah"
    true -> "xyz[aa:bb]:blah"
    

    The best guesses I have, not seeing your actual code:

    • you are using a skipper that eats some of your characters (see Boost spirit skipper issues)

    • you are using an input iterator that interferes

    • you're invoking UB. To be honest, without context, this seems the most likely

    If you show more code I'll happily diagnose which it is.